您的位置:首页 > 其它

Best Time to Buy and Sell Stock III 解答

2015-09-21 07:23 375 查看

Question

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

Solution

This problem can be solved by "divide and conquer". We can use left[i] array to track maximum profit for transactions before i (including i), and right[i + 1] to track maximum profit for transcations after i.

Prices: 1 4 5 7 6 3 2 9
left = [0, 3, 4, 6, 6, 6, 6, 8]
right= [8, 7, 7, 7, 7, 7, 7, 0]

Time complexity O(n), space cost O(n).

public class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length < 2)
return 0;
int length = prices.length, min = prices[0], max = prices[length - 1], tmpProfit = 0;
int[] leftProfits = new int[length];
leftProfits[0] = 0;
int[] rightProfits = new int[length];
rightProfits[length - 1] = 0;
// Calculat left side profits
for (int i = 1; i < length; i++) {
if (prices[i] > min)
tmpProfit = Math.max(tmpProfit, prices[i] - min);
else
min = prices[i];
leftProfits[i] = tmpProfit;
}
// Calculate right side profits
tmpProfit = 0;
for (int j = length - 2; j >= 0; j--) {
if (prices[j] < max)
tmpProfit = Math.max(tmpProfit, max - prices[j]);
else
max = prices[j];
rightProfits[j] = tmpProfit;
}
// Sum up
int result = Integer.MIN_VALUE;
for (int i = 0; i < length - 1; i++)
result = Math.max(result, leftProfits[i] + rightProfits[i + 1]);
result = Math.max(result, leftProfits[length - 1]);
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: