⓹➈ Best Time to Buy and Sell Stock II

Top Interview 150, leetcode easy, C++, Algorithm

Today’s code

capacity from leetcode

延續上一篇題目>>>>

我們遇到比買價高的price就計算profit,並累積總profit。並且同時要去更新buy_price,新的買價。

class Solution {
public:
int maxProfit(vector<int>& prices) {
int length = prices.size();
int max_profit = 0;
int buy_price = prices[0];
int profit = 0;
int i = 0;
while(i < length){
if(buy_price < prices[i]){
profit = prices[i] - buy_price;
buy_price = prices[i];
max_profit += profit;
}else{
buy_price = prices[i];
}
i++;
}
return max_profit;
}
};

--

--