买卖股票的最佳时机 III
题目描述
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。
设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意:你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
示例
官解思路
采用动态规划思想,由于我们最多可以完成两笔交易,因此在任意一天结束之后,我们会处于以下五个状态中的一种:
未进行过任何操作;
只进行过一次买操作;
进行了一次买操作和一次卖操作,即完成了一笔交易;
在完成了一笔交易的前提下,进行了第二次买操作;
完成了全部两笔交易。
Java代码
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int buy1 = -prices[0], sell1 = 0;
int buy2 = -prices[0], sell2 = 0;
for(int i = 1; i< n; i++) {
buy1 = Math.max(buy1, -prices[i]);
sell1 = Math.max(sell1, buy1 + prices[i]);
buy2 = Math.max(buy2, sell1 - prices[i]);
sell2 = Math.max(sell2, buy2 + prices[i]);
}
return sell2;
}
}
java 代码2
class Solution {
public int maxProfit(int[] prices) {
int n = prices.length;
int cache[][] = new int[n][2];
cache[0][0] = 0;
cache[n-1][1] = 0;
int min = prices[0];
for(int i = 1; i < n; i++){
int cur = prices[i];
min = Math.min(cur, min);
cache[i][0] = Math.max(cache[i-1][0], Math.max(0, cur - min));
}
int max = prices[n - 1];
for(int i = n - 2; i >= 0; i--){
int cur = prices[i];
max = Math.max(cur, max);
cache[i][1] = Math.max(cache[i+1][1], Math.max(0, max - cur));
}
int res = 0;
for(int[] c: cache) res = Math.max(res, c[0]+c[1]);
return res;
}
}