---
# System prepended metadata

title: 122-Best Time to Buy and Sell Stock II
tags: [Medium]

---

# 122-Best Time to Buy and Sell Stock II
###### tags: `Medium`
## Question
![](https://i.imgur.com/9ZGvSJh.png)
https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/

## Solution
- 想法:因為可以當天賣出又買進，所以就算最低跟最高不是在前後兩天，一直買進賣出獲利一樣可以等於最低買最高賣，因此只做前後兩個差值的計算，就可以找到整個陣列最大的差值總和


### C++
```cpp=
lass Solution {
public:
    int maxProfit(vector<int>& prices) {
        int buy = prices[0];
        int max = 0;
        int sell = 0;
        for(int i = 1; i < prices.size();i++)
        {
            sell = prices[i];
            if(sell - buy > 0)
            {
                max += sell - buy;
            }
            buy = prices[i];
        }
        return max;
    }
};
```
### python
```python=
class Solution:
    def maxProfit(self, prices):
        
        profit = 0
        
        for i in range(len(prices)-1):
            if prices[i+1] - prices[i] > 0:
                profit += prices[i+1] - prices[i]
        
        return profit
```