LeetCode 121 Best Time to Buy and Sell Stock - Example and Complexity Analysis

Walkthrough and analysis

Trace prices = [7, 1, 5, 3, 6, 4].

Initialize: minPrice = infinity, maxProfit = 0.

Day 1: price = 7. Update minPrice = 7. Profit = 7 - 7 = 0. maxProfit = 0.

Day 2: price = 1. Update minPrice = 1. Profit = 1 - 1 = 0. maxProfit = 0.

Day 3: price = 5. minPrice = 1. Profit = 5 - 1 = 4. Update maxProfit = 4.

Day 4: price = 3. minPrice = 1. Profit = 3 - 1 = 2. maxProfit stays 4.

Day 5: price = 6. minPrice = 1. Profit = 6 - 1 = 5. Update maxProfit = 5.

Day 6: price = 4. minPrice = 1. Profit = 4 - 1 = 3. maxProfit stays 5.

Return 5.

One pass through nn elements. That's O(n)O(n) time. Only two variables tracked. That's O(1)O(1) space.