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:
Input: [3,3,5,0,0,3,1,4]
Output: 6
Explanation: Buy on day 4 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3.
Then buy on day 7 (price = 1) and sell on day 8 (price = 4), profit = 4-1 = 3.
Example 2:
Input: [1,2,3,4,5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.
Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are
engaging multiple transactions at the same time. You must sell before buying again.
Example 3:
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.
- Method1:DP
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length <= 1) return 0;
int[] local = new int[3];
int[] global = new int[3];
for(int i = 0; i < prices.length - 1; i++){
int diff = prices[i + 1] - prices[i];
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];
}
}
- (Wrong)I tried my best to solve this question but cannot pass one case: [1,2,4,2,5,7,2,4,9,0], maybe I can use recursion to solve this question, but not a good idea.
class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0) return 0;
int first = 0, second = 0, pre = -1, temp = 0;;
for(int i = 1; i < prices.length; i++){
if(prices[i] < prices[i - 1]){
temp = pre == -1 ? prices[i - 1] - prices[0] : prices[i - 1] - prices[pre];
pre = i;
if(temp >= first){
second = first;
first = temp;
}else if(temp > second) second = temp;
}
}
if(pre == -1) return prices[prices.length - 1] - prices[0];
if(pre != prices.length - 1){
temp = prices[prices.length - 1] - prices[pre];
if(temp >= first){
second = first;
first = temp;
}else if(temp > second) second = temp;
}
return first + second;
}
}
- Method 1: DP
class Solution { public int maxProfit(int[] prices) { if(prices == null || prices.length <= 1) return 0; int len = prices.length; int[][] buys = new int[len + 1][3]; int[][] sells = new int[len + 1][3]; buys[1][1] = -prices[0]; buys[1][2] = Integer.MIN_VALUE; for(int i = 2; i <= len; i++){ for(int j = 1; j <= 2; j++){ buys[i][j] = Math.max(buys[i - 1][j], sells[i - 1][j - 1] - prices[i - 1]); sells[i][j] = Math.max(sells[i - 1][j], buys[i - 1][j] + prices[i - 1]); } } return Math.max(sells[len][0], Math.max(sells[len][1], sells[len][2])); } }