[leetcode]123. Best Time to Buy and Sell Stock III 最佳炒股时机之三

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 (i.e., you must sell the stock before you buy again).

Example 1:

题目

和之前一样,这次你至多能买卖两次。

思路

1. Split the array into two parts, one trade each.

2. Say that f(i) stands for max profit in [0,i] , g(i) stands for max profix in [i, n-1] , then update and finally return max(f(i) + g(i))

代码

 // Best Time to Buy and Sell Stock III
// 时间复杂度O(n),空间复杂度O(n)
public class Solution {
public int maxProfit(int[] prices) {
if (prices.length < 2) return 0; final int n = prices.length;
int[] f = new int[n];
int[] g = new int[n]; for (int i = 1, valley = prices[0]; i < n; ++i) {
valley = Math.min(valley, prices[i]);
f[i] = Math.max(f[i - 1], prices[i] - valley);
} for (int i = n - 2, peak = prices[n - 1]; i >= 0; --i) {
peak = Math.max(peak, prices[i]);
g[i] = Math.max(g[i], peak - prices[i]);
} int max_profit = 0;
for (int i = 0; i < n; ++i)
max_profit = Math.max(max_profit, f[i] + g[i]); return max_profit;
}
}
上一篇:LeetCode 123. Best Time to Buy and Sell Stock III (stock problem)


下一篇:Java for LeetCode 123 Best Time to Buy and Sell Stock III【HARD】