要求
代码
class Solution {
public:
int maxProfit(vector<int>& prices) {
int min_price = prices[0];
int benefit = 0;
for (int i = 0; i < prices.size(); i++)
{
benefit = max(benefit, prices[i] - min_price);
min_price = min(min_price, prices[i]);
}
return benefit;
}
};
这里最开始使用暴力解法,两个for循环来跑leetcode报超时的错误,显然运行时间过长了。
考虑使用一遍for循环,每次判断这次的价格和历史最低价的差值,即利润,是否大于历史利润,来更新利润,使用一次for循环可以解决。