思想:用一个flag把区间分为两部分,找到两部分各自的谷(买入)和峰(卖出)。从0到n移动flag遍历数组。
注意:这里代码并没有flag,只不过分两次把flag的两部分遍历找了出来。
参考答案:
class Solution
{
public: /**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
* 两次交易所能获得的最大收益
* @param prices int整型vector 股票每一天的价格
* @return int整型 */
int maxProfit(vector<int> prices)
{
int n = prices.size();
int money = prices[0];
vector<int> first(n, 0);
for (int i = 1; i < n; ++i)
{
money = min(money, prices[i]);
first[i] = max(first[i - 1], prices[i] - money);
}
vector<int> second(n, 0);
money = prices[n - 1];
for (int i = n - 2; i >= 0; --i)
{
money = max(money, prices[i]);
second[i] = max(second[i + 1], money - prices[i]);
}
int ans = 0;
for (int i = 0; i < n; ++i)
ans = max(ans, first[i] + second[i]);
return ans;
}
};


京公网安备 11010502036488号