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 (i.e., buy one and sell one share of the stock), design an algorithm to find the maximum profit.
Note that you cannot sell a stock before you buy one.
Example 1:
1 | Input: [7,1,5,3,6,4] |
Example 2:
1 | Input: [7,6,4,3,1] |
动态规划
设立两个变量 profit 和 min
对于i 从0 遍历到price.size()-1, profit存储了从0到i的最大利润,min存储了从0到i的最小值。
当i更新到i+1时,重新计算i+1是否是更小的值,与前面的min比较。同时计算i+1的加入是否产生了更大的profit。 price[i+1]-min与profit比较。
- 此题可以这样做的关键在于,对于第i+1个加入的元素,只需要前i个元素中的最小值即可求出maxprofit,能在O(1)时间完成
1 | class Solution { |