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:
public class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE, maxPro = 0;
for (int price : prices) {
minPrice = Integer.min(price, minPrice);
maxPro = Integer.max(maxPro, price - minPrice);
}
return maxPro;
}
}
思路2:
设buy[i]表示第i天 手里仍有未卖出的股票 最大利润。sell[i]表示第i天手里已经没有未卖出的股票 获得的最大利润。
状态转移方程为:
buy[i] = max{buy[i-1],-prices[i-1]} , i>=1&&i<=n
sell[i] = max{sell[i-1],buy[i]+prices[i-1]} i>=1&&i<=n
其中buy[i]的作用相当于在前i天中选一个价格最小的,这样有可能会获得最大利润。
但是光买的时候价格最低没有用,需要两天的价格差值最大才可以。比如 价格序列为5,10,1,2 这样的话,价格最低的是1,1后面只有2了,所以得到的最大利润是1,显然是错误的。
所以需要sell来控制最大的差值,buy会更新成最小的价格,但是更新了不一定会有用,最后由sell来控制最大的差值。
但是sell和buy的更新只用到了前一天的数据,所以优化成如下:
buy = max{buy,-prices[i-1]}
sell = max{sell,buy+prices[i-1]} i>=1&&i<=n
public class Solution {
public int maxProfit(int[] prices) {
int buy = Integer.MIN_VALUE, sell = 0;
for (int price : prices) {
buy = Integer.max(buy, -price);
sell = Integer.max(sell, buy + price);
}
return sell;
}
}