题解
class Solution {
public:
int maxProfit(vector<int>& prices) {
int size_ = prices.size();
if(prices.size() < 2)
return 0;
int in = -1, profit; // 买入价格和当前利润
int total = 0; // 总利润
for(int i = 0;i < size_ - 1; i++){
if(in == -1 && prices[i] < prices[i + 1]){
in = prices[i];
continue;
}
if(in != -1 && i < size_ - 1){
if(prices[i] < prices[i + 1]){
profit = prices[i + 1] - in;
}
else {
profit = prices[i] - in;
in = -1;
total += profit;
}
}
}
if(in != -1)
total += prices[size_-1] - in;
return total;
}
};
思路
这题easy,没什么可说的非要说的话就是测试数据不讲武德,哪有股票价格是0的,那不买爆?