题目描述
Say you have an array for which the i th element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete at most two transactions.
Note:
You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
看了大佬的题解,意识到回家养猪真的是一个不错的选择。
先上代码:
public class Solution {
public int maxProfit(int[] prices) {
int buy1 = Integer.MIN_VALUE, buy2 = Integer.MIN_VALUE;
int sell1 = 0, sell2 = 0;
for(int i = 0; i < prices.length; ++i){
buy1 = Math.max(buy1, -prices[i]);
sell1 = Math.max(sell1, prices[i] + buy1);
buy2 = Math.max(buy2, sell1 - prices[i]);
sell2 = Math.max(sell2, buy2 + prices[i]);
}
return sell2;
}
}
sell1即为第一次卖出后剩下的钱。buy2为第二次买入,买入后剩下的钱,sell2为最终结果。
一开始看到这个题解我是蒙逼的,因为sell1这样找到最后不就是最大结果了吗?
没错,sell1当循环结束的时候确实是最大结果。但是buy2并不会更新。buy2的更新是在sell1已经计算出来的基础上进行迭代的,所以sell1找到一个最大值的时候,buy2开始继续从此位置向后找。sell1更新在前,就算最后sell1为最大差值,sell2如果没有更好的买卖选择,也是不会更新掉的。思想应该也属于动态规划。