目录
121 买卖股票的最佳时机
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0;
int now = prices[0];
for(int i = 1;i < prices.size();i++){
if(prices[i] > now){
res = max(res,prices[i] - now);
}
now = min(now,prices[i]);
}
return res;
}
};
时间复杂度O(n)
空间复杂度O(1)
122 买卖股票的最佳时机 ||
class Solution {
public:
int maxProfit(vector<int>& prices) {
int res = 0;
int now = prices[0];
for(int i = 1;i < prices.size();i++){
if(prices[i] > now)res += prices[i] - now;
now = prices[i];
}
return res;
}
};
时间复杂度O(n)
空间复杂度O(1)