c++代码
首先想到暴力解法,这是最直观的O(n^2) O(1) 会超时
class Solution {
public:
int maxProfit(vector<int>& prices)
{
int profit = 0;
int len = prices.size();
for (int i = 0; i < len - 1; i++)
{
for (int j = i + 1; j < len; j++)
{
profit = max(profit, prices[j] - prices[i]);
}
}
return profit;
}
};
改进一下,只要一遍for循环
class Solution {
public:
int maxProfit(vector<int>& prices)
{
int len = prices.size();
if (len < 2) //不足两天肯定没法赚钱
return 0;
int min_buy = prices[0];
int profit = 0;
for (int i = 0; i < len - 1; i++)
{
min_buy = min(min_buy, prices[i]);
profit = max(profit, prices[i + 1] - min_buy); //时刻更新
}
return profit;
}
};