# 122. Best Time to Buy and Sell Stock II

<https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii/>

Comparing to first one, this problem can buy and sell several times, first one only do once time. 第一題只能買賣一次, 這題可以買賣多次

```java
/*
    greedy
    
    time complexity: O(n), space complexity:O(1)
*/
class Solution {
    public int maxProfit(int[] prices) {
        int profit = 0;
        for (int i = 0; i < prices.length - 1; i++) { // or add  i+1 < prices.length &&  in if statement
            if (prices[i+1] > prices[i]) { // found next price is bigger, add it to profit
                profit += prices[i+1] - prices[i];
            }
        }
        return profit;
    }
}
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/greedy/122.-best-time-to-buy-and-sell-stock-ii.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
