給予一陣列 prices
, prices[i]
代表第 i
天時的股票價錢,回傳我們可以在這幾天中最多可以賺到多少錢,限制最多只能做兩次買進買出。但是你不能同時在還沒賣掉手上股票前,又買入另一天的股票 (手上沒股票時才能買股票)。
class Solution {
public:
int maxProfit(vector<int>& prices)
{
int t1minCost = INT_MAX, t2minCost = INT_MAX;
int t1maxProfit = 0, t2maxProfit = 0;
for (int price : prices)
{
t1minCost = min(t1minCost, price);
t1maxProfit = max(t1maxProfit, price - t1minCost);
t2minCost = min(t2minCost, price - t1maxProfit);
t2maxProfit = max(t2maxProfit, price - t2minCost);
}
return t2maxProfit;
}
};
or
By clicking below, you agree to our terms of service.
New to HackMD? Sign up