您的位置:首页 > 其它

【LintCode】 Best Time to Buy and Sell Stock III 买卖股票的最佳时机 III

2015-07-30 10:05 489 查看
假设你有一个数组,它的第i个元素是一支给定的股票在第i天的价格。设计一个算法来找到最大的利润。你最多可以完成两笔交易。

样例

给出一个样例数组 [4,4,6,1,1,4,2,5], 返回 6

注意

你不可以同时参与多笔交易(你必须在再次购买前出售掉之前的股票)

class Solution {
/**
* @param prices: Given an integer array
* @return: Maximum profit
*/
public int maxProfit(int[] prices) {
if(null == prices || prices.length < 2)return 0;
int[] profitLeft =  new int[prices.length];
int[] profitRight = new int[prices.length];

int minPrice = prices[0];
for(int i = 1; i < prices.length; i++) {
profitLeft[i] = Math.max(profitLeft[i - 1], prices[i] - minPrice);
minPrice = Math.min(minPrice, prices[i]);
}

int maxPrice = prices[prices.length - 1];
for(int i = prices.length - 2; i >= 0; i--) {
profitRight[i] = Math.max(profitRight[i + 1], maxPrice - prices[i]);
maxPrice = Math.max(maxPrice, prices[i]);
}

int result = 0;
for(int i = 0; i < prices.length; i++) {
result = Math.max(result, profitLeft[i] + profitRight[i]);
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: