当天对比当天的,如果符合条件就换;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int inf = 1e9;
int minp = inf, maxprofit = 0;
int n = prices.size();
for(int i = 0; i < n; i++){
minp = min(minp, prices[i]);
maxprofit = max(maxprofit, prices[i] - minp);
}
return maxprofit;
}
};
每天只要有利润tmp >0 就卖这个不符合题意,但是累加起来就是买的那天和卖的那天的利润,结果是一样的,只要结果就行了;
class Solution {
public:
int maxProfit(vector<int>& prices) {
int profit = 0;
int n = prices.size();
for(int i = 1; i < n; i++)
{
int tmp = prices[i] - prices[i-1];
if(tmp > 0){
profit += tmp;
}
}
return profit;
}
};