Problem: Given an array price[], price[i] denotes the stock price at day i. Assume the array has a length of N (from day 1 to day N), try to get the maximum profit by selecting optimal timing to bug and sell stocks. For example, if price[] = {5, 2, 4, 3, 1}, the maximum profit per share we can get is $2. What we need to do is buy at day 2 and sell at day 3.
Solution: Naive approach takes O(N^2) by checking any two days. An improved approach costs O(NlogN) by first finding a descending sequence from the beginning. However, optimal approach should only cost O(N). The key is to do some transformation on the original problem. Let us still reuse the previous example, given price[] = {5, 2, 4, 3, 1}, we can get another array diff[] = {-3, 2, -1, -2} such that diff[i] = price[i] - price[i-1] . Then other goal is just to find the maximum subarray in diff[]. As known, there is a O(N) solution for the maximum subarray problem.
More: An alternative that may be conceptually even simpler exist. Just do a linear scan, we keep a current_min, then for every day, we calculate the gain as the difference between the price at that day and current_min,if the gain is more than the maximum gain that we are tracking, update the maximum.
This algorithm also takes O(N).
No comments:
Post a Comment