买卖股票的最佳时机 II
题目描述
给你一个整数数组 prices ,其中 prices[i] 表示某支股票第 i 天的价格。
在每一天,你可以决定是否购买和/或出售股票。你在任何时候 最多 只能持有 一股 股票。你也可以先购买,然后在 同一天 出售。
返回 你能获得的 最大 利润 。
解题思路
很简单,只要相隔的两天股票是涨价我就买卖,如果是连续涨价可以看成中间那天我先卖后买,等于没有买卖就行了。然后就是求差值,把差值为正的加上就行,很简单的一题。
题解
class Solution {
public:
int maxProfit(vector<int>& prices) {
int ans = 0;
int profile;
for(int i = 1; i < prices.size(); i++){
profile = prices[i] - prices[i - 1];
if(profile > 0){
ans += profile;
}
}
return ans;
}
};