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 1:
Input: [7, 1, 5, 3, 6, 4]
Output: 5
max. difference = 6-1 = 5 (not 7-1 = 6, as selling price needs to be larger than buying price)
Example 2:
Input: [7, 6, 4, 3, 1]
Output: 0
In this case, no transaction is done, i.e. max profit = 0.
解法1:DP with O(N) 空间
从左往右维护一个最小的price,那么转换方程就可以写成dp[i] = Math.max(dp[i - 1], price[i] - min),
其中dp[i]表示的是前i个数中如果只能交易一次的最大利润,不一定要以i结尾。
解法2:DP with O(1) 空间
从左往右维护当前的最小值,并且计算每一个累积和和最小值的差,取最大的作为结果.
这题用DP的思路是dp[i] = max(dp[i - 1], A[i] - min), 所以就是也要维护一个min,实际上并不需要维护dp数组,只要不停更新min就可以了