Problem
Problem page: https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
Topics: Array Dynamic Programming
Difficulty: Medium
Say you have an array for which the ith element is the price of a given stock on day i.
If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Analysis
Since we're only allowed one transaction, one pass through the array is enough to find the largest difference. But the maximum has to come to the right of the minimum. We can't just find the maximum and minimum and subtract the two, since that might give us the "maximum loss". The right way is to go through the array once, keeping track of the smallest value seen so far. At each element, subtract that minimum from the current value and keep track of the largest difference so far.
The original problem calls this dynamic programming. Maybe this is what's called one-dimensional dynamic programming? I've never quite got the hang of the definition of dynamic programming... Maybe I can think of it this way: if I can break a problem down and solve it step by step by building on solutions to subproblems, a bit like mathematical induction, then it's dynamic programming. The number of dimensions in the dynamic programming problem is the number of dimensions along which I can break it into subproblems. Here I can break it down by day, so it's one-dimensional dynamic programming. In the 0/1 knapsack problem, I can break it down along two dimensions, knapsack capacity and items, so it's two-dimensional dynamic programming.
Code
1 | class Solution: |
Article link: https://xnerv.wang/en/leetcode-best-time-to-buy-and-sell-stock/
