题目描述
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
Find the maximum profit you can achieve. You may complete at most two transactions.
Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).
Example 1:
Input: prices = [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: prices = [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: prices = [7,6,4,3,1] Output: 0 Explanation: In this case, no transaction is done, i.e. max profit = 0.
解题思路
【C++】
1. 左右开工
class Solution {
public:
int maxProfit(vector<int>& prices) {
if(prices.empty()) return 0;
int minprice = prices[0];
int maxprice = prices[prices.size()-1];
int profit1 = 0;
int profit2 = 0;
int profit = 0;
vector<int> a;
for(int i = 0; i < prices.size(); i++){
profit1 = max(profit1, prices[i] - minprice);
minprice = min(minprice, prices[i]);
a.push_back(profit1);
}
for(int i = prices.size() - 2; i >= 0; i--){
maxprice = max(maxprice, prices[i]);
profit2 = max(profit2, maxprice - prices[i]);
profit = max(profit,profit2 + a[i]);
}
return profit;
}
};
2. 一趟公式
profit1 = x2 - minx1, profit2 = x4 = minx3, minx3 >= x2
profit = profit1 + profit 2 = x4 - min(x3 - profit1)
class Solution {
public:
int maxProfit(vector<int>& prices) {
int min1 = INT_MAX, min2 = INT_MAX, profit1 = 0, profit2 = 0;
for (auto x : prices){
min1 = min(min1, x);
profit1 = max(profit1, (x-min1));
min2 = min(min2, (x-profit1));
profit2 = max(profit2, (x-min2));
}
return profit2;
}
};
【Java】
class Solution {
public int maxProfit(int[] prices) {
int min1 = Integer.MAX_VALUE, min2 = Integer.MAX_VALUE, profit1 = 0, profit = 0;
for (int x : prices) {
min1 = Math.min(x, min1);
profit1 = Math.max(profit1, x - min1);
min2 = Math.min(min2, x - profit1);
profit = Math.max(profit, x - min2);
}
return profit;
}
}