Vilochen.
递归方式:
public int maxProfit2(int[] prices) {
return Math.max(maxProfit2(prices, 0, true)
, maxProfit2(prices, 0, false));
}
public int maxProfit2(int[] prices, int i, boolean buy) {
if (i >= prices.length - 1) {
return 0;
}
if (buy) {
int sum = 0;
if (prices[i] < prices[i + 1]) {
sum = prices[i + 1] - prices[i];
}
return Math.max(maxProfit2(prices, i + 1, true)
, maxProfit2(prices, i + 1, false)) + sum;
} else {
return Math.max(maxProfit2(prices, i + 1, true)
, maxProfit2(prices, i + 1, false));
}
}