题目:
给定一个数组,它的第 i 个元素是一支给定的股票在第 i 天的价格。设计一个算法来计算你所能获取的最大利润。你最多可以完成 两笔 交易。
注意: 你不能同时参与多笔交易(你必须在再次购买前出售掉之前的股票)。
class Solution {
public int maxProfit(int[] prices) {
int max = 0;
for (int i = 0; i < prices.length; i++) {
max = Math.max(max, func(prices, 0, i) + func(prices, i, prices.length));
}
return max;
}
private int func(int[] prices, int start, int end) {
int min = prices[start];
int profit = 0;
for (int i = start; i < end; i++) {
profit = Math.max(prices[i] - min, profit);
min = Math.min(min, prices[i]);
}
return profit;
}
}