LeetCode 123. Best Time to Buy and Sell Stock III
最多只能交易两次 求最大可以获得利润
class Solution {
public int maxProfit(int[] prices) {
int t1Cost = Integer.MAX_VALUE,
t2Cost = Integer.MAX_VALUE;
int t1Profit = 0,
t2Profit = 0;
for (int price : prices) {
// the maximum profit if only one transaction is allowed
t1Cost = Math.min(t1Cost, price); //成本为正 取最小
t1Profit = Math.max(t1Profit, price - t1Cost); //维护一个最大的利润值
// reinvest the gained profit in the second transaction
t2Cost = Math.min(t2Cost, price - t1Profit); //成本依然取最小 但是不一样的是我们因为之前赚了t1Profit的钱 因此要从成本里面扣掉
t2Profit = Math.max(t2Profit, price - t2Cost); //利润既然取最大
}
return t2Profit;
}
}
这个答案就是完完全全从LC21演变过来的

浙公网安备 33010602011771号