Best Time to Buy and Sell Stock
Question
http://www.lintcode.com/en/problem/best-time-to-buy-and-sell-stock/
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.
Example
Given an example [3,2,3,1,2], return 1
Analysis
最初的想法是问题可以转化一下:计算相邻两天的变化量array,再对这个差值array寻找maximum subarray,得到的maximum也就是对应的maximum profit
另一种想法是:仅记录loop过的历史最小值,再寻找当前profit最大值.
Time complexity: O(n)
. Only a single pass is needed.
Space complexity: O(1)
. Only two variables are used.
Solution
One pass - record lowest price O(n) (1ms 99.88% AC)
One Pass
Reference
Best Time to Buy and Sell Stock Series: I, II, III, IV
Last updated
Was this helpful?