> For the complete documentation index, see [llms.txt](https://jenhsuan.gitbook.io/algorithm/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://jenhsuan.gitbook.io/algorithm/leetcode/122.-best-time-to-buy-and-sell-stock-ii.md).

# 122. Best Time to Buy and Sell Stock II

## 1.問題&#x20;

* **股票最高獲利? (可以買賣多次)**

![](/files/-LNP0PBpksX3I3DCS8nl)

## 2.想法 <a href="#id-2-xiang-fa" id="id-2-xiang-fa"></a>

* 提問
  * 確認題意: &#x20;
* function header, parameter
* test input
* 觀察
  * 有點像是動態規劃的概念, 假設買賣只差了一天, 那麼每天所記錄的就是兩天間的價差
* 說明想法
  * 將正的價差全部相加
* 測試計算複雜度

## **3.程式碼** <a href="#id-3-cheng-shi" id="id-3-cheng-shi"></a>

```
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int sum = 0;
        for (int i = 1; i < prices.size(); i++) {
            int tmp = prices[i] - prices[i - 1];
            if (tmp > 0) {
                sum += tmp;
            }
        }
        
        return sum;
    }
};
```
