题目
Say you have an array for which the ith 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).
题意解读:给定一个数组,数组的第i个元素是第i天的股票价格。你最多可以进行两次交易。求最大的利润
//限制交易次数为两次 这两次买卖在时间跨度上不能有重叠 既然不能有重叠可以将整个序列以任意坐标i为分割点,分割成两部分:
//set[0,n] = set[0,i]+set[i,n]
//先从左到右进行遍历 状态转移方程为d[i] = max(d[i-1],d[i]-min)
//再从右到左进行遍历 状态转移方程为d[j-1] = max(max-d[j-1],d[j-1]) dp[i]代表[j,n]交易能达到的最大收益
//对于这个特定分割来说,最大收益为两段的最大收益之和。每一段的最大收益当然可以用I的解法来做。而III的解一定是对所有0<=i<=n-1的分割的最大收益中取一个最大值。
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length==0) return 0;
int[] dpl = new int[prices.length];
int[] dpr = new int[prices.length];
int[] dp = new int[prices.length];
//从左到右开始遍历
int minPrice = prices[0];
for(int i = 1; i < prices.length; i++){
minPrice = Math.min(minPrice,prices[i]);
dpl[i] = Math.max(dpl[i-1],prices[i]-minPrice);
}
//从右往左开始遍历
int maxPrice = prices[prices.length-1];
for(int j = prices.length-2; j >= 0; j--){
maxPrice = Math.max(maxPrice,prices[j]);
dpr[j] = Math.max(dpr[j+1],maxPrice-prices[j]);
}
for(int k = 0;k < prices.length; k++)
dp[k] = dpl[k] + dpr[k];
Arrays.sort(dp);
return dp[prices.length-1];
}
}