题目链接:https://leetcode.com/problems/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 (ie, you must sell the stock before you buy again).
解题思路:
这题的考点是动态规划。
这题是 188 Best Time to Buy and Sell Stock IV 这题的特殊情况。即 k = 2 时。
代码实现:
public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0)
return 0;
int[] local = new int[3];
int[] global = new int[3];
for(int i = 1; i < prices.length; i ++) {
int diff = prices[i] - prices[i - 1];
for(int j = 2; j >= 1; j --) {
local[j] = Math.max(global[j - 1] + Math.max(diff, 0), local[j] + diff);
global[j] = Math.max(global[j], local[j]);
}
}
return global[2];
}
}
198 / 198 test cases passed.
Status: Accepted
Runtime: 9 ms