您的位置:首页 > 其它

[leetcode] Best Time to Buy and Sell Stock III

2015-11-26 13:56 357 查看
题目:

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).


分析:把数组一分为二,正序求最大值并保存到一个数组,然后反序求最大值并保存到另一个数组,最后这两个数组相加求最终最大值即可。

代码(可参考Best Time to Buy and Sell Stock):

public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0)
return 0;
int[] result1 = new int[prices.length];//保存正序扫描的最大收益
int[] result2 = new int[prices.length];//保存反序扫描的最大收益
int min = prices[0], max = prices[0];
int result = 0;
for (int i = 1; i < prices.length; i++) {//正序扫描
if (prices[i] > max) { // 实时计算并保存最大收益
max = prices[i];
if (max - min > result) {
result = max - min;
}
} else if (prices[i] < min) { // 重新规定查找区域
min = prices[i];
max = prices[i];
}
result1[i] = result;
}
min = prices[prices.length-1]; max = prices[prices.length-1]; result = 0;
for (int i = prices.length-2; i >= 0; i--) {//反序扫描
if (prices[i] < min) { // 实时计算并保存最大收益
min = prices[i];
if (max - min > result) {
result = max - min;
}
} else if (prices[i] > max) { // 重新规定查找区域
min = prices[i];
max = prices[i];
}
result2[i] = result;
}
int max_profit = 0;
for (int i = 0; i < prices.length; i++) {//叠加求和,输出最大值
if (result1[i] + result2[i] > max_profit) {
max_profit = result1[i] + result2[i];
}
}
return max_profit;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: