---
# System prepended metadata

title: Leetcode 122. Best Time to Buy and Sell Stock II
tags: [Leetcode, Array, Greedy]

---

## 貪婪解法

計算出前一天和今天的價差總和

```python=
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        totalLength = len(prices)
        totalProfit = 0
        left = 0
        right = 1

        while right < totalLength:
            currentProfit = prices[right] - prices[left]
            if currentProfit < 1:
                left = right
            else:
                totalProfit += currentProfit
                left = right
            right += 1

        return totalProfit
```

2023.08.18 AC

```python=
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        output = 0
        for i in range(1,len(prices)):
            if prices[i] >= prices[i-1]:
                output += prices[i] - prices[i-1]
        return output
```