Best Time to Buy and Sell Stock
Question 1 (LC.121)
Example
Input: [7, 1, 5, 3, 6, 4]
Output: 5 Buy at 1 and sell at 6Analysis
Approach
1. optimal subproblems
maxProfit(n) = maximum profit you can get at day n
2. solve by prefix
maxProfit(n) = Math.max(maxProfit(n-1), prices[n] - localMin)
3. topo order
for i from 2 to n
4. base cases
maxProfit(0) = 0
5. answer
return maxProfit(n)Code
Time & Space Complexity
Follow Up #1
Analysis
Code
Time Complexity
Question 2
Last updated