Say you have an array for which the i th 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).
C++
class Solution {
public:
int maxProfit(vector<int>& prices){
int buy1 = INT_MIN;
int sell1 = 0;
int buy2 = INT_MIN;
int sell2 = 0;
for(int i = 0; i< prices.size(); i++){
buy1 = max(buy1,-prices[i]);
sell1 = max(sell1,buy1 + prices[i]);
buy2 = max(buy2, sell1 - prices[i]);
sell2 = max(sell2,buy2 + prices[i]);
}
return sell2;
}
};

本文介绍了一种算法,用于计算给定股票价格数组中通过至多两笔交易获得的最大利润。该算法遵循特定规则:不能同时进行多次交易,即卖出股票后才能再次购买。通过四个变量跟踪买入和卖出的最佳时机。
373

被折叠的 条评论
为什么被折叠?



