121. 买卖股票的最佳时机
//暴力解法 通过不了
class Solution {
public:
int maxProfit(vector<int>& prices) {
//两层循环 找出数组中两个元素之间最大差值
int maxprofit = 0;
for(int i = 0; i < prices.size() - 1; i++)
{
for(int j = i + 1; j < prices.size(); j++)
{
maxprofit = max(maxprofit,prices[j] - prices[i]);
}
}
return maxprofit;
}
};
//minpice记录历史最低价格 前i - 1个价格最低的一个
//所以先算利润 再更新历史最低点价格
class Solution {
public:
int maxProfit(vector<int>& prices) {
int inf = 1e9;//初始化无穷大
int minprice = inf,maxprofit = 0;
for(int price: prices)
{
maxprofit = max(maxprofit,price - minprice);
minprice = min(price,minprice);
}
return maxprofit;
}
};