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).
一刷
題解:
dp的原理,但是數組長度為常數。
hold[2], sold[2]分別表示:hold[0], hold[1]表示第一次買入, 第二次買入的最小代價,sold[0], sold[1]表示第一,第二次賣出后的最大利潤。
注意,更新順序為sold[0], hold[0], sold[1], hold[1], 因為hold[I]需要根據sold[I]的信息。
public class Solution {
public int maxProfit(int[] prices) {
int[] hold = new int[2];
int[] sold = new int[2];
Arrays.fill(hold, Integer.MIN_VALUE);
for(int price : prices){
sold[0] = Math.max(price + hold[0], sold[0]);
hold[0] = Math.max(hold[0], -price);//hold the minimum number
sold[1] = Math.max(sold[1], price + hold[1]);
hold[1] = Math.max(hold[1], sold[0] - price);
}
return sold[1];
}
}