# Best Time to Buy and Sell Stock II

You are given an array `prices` where `prices[i]` is the price of a given stock on the `ith` day. Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

**Note:** You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

### Approach:

The general idea is to buy stock at valleys (lowest price) and then sell stock at its next peak (highest price). In the below drawing, there are two valleys and two peaks. Since (1) we have to buy stock before selling it and (2) we can not have back-to-back buy or sell trades, thus there are two options of trading stocks.&#x20;

Option 1: Buy stock at `valley[1]` then sell at `peak[5]` makes profit **`A (peak[5] - valley[1])`**. Then buy stock at `valley [3]` and sell at `peak[6]` makes profit **`B (peak[6] - valley[3])`**. So the total profit of this trade option is **A + B**.&#x20;

Option 2: Skip the intermediate trades, i.e,, we buy stock at `valley[1]` then sell at `peak[6]`. In this case, the total profit will be **`C (peak[6]-valley[1])`**.&#x20;

Based on the graph shown below, **A + B > C --> 4 + 3 > 6** (if not, peak\[i] and valley\[j] won't exist). So in order to maximize the profit, we can buy stock at valleys and then sell stock at peaks.

*I've drawn the below illustration to help conceptualize this problem:*

![](https://2282290372-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MJcwT61yCiz5H4ZddkF%2F-MfxD3TcTuA-PwxMW5kd%2F-MfxFbM0Qre7czV1YFEP%2Fimage.png?alt=media\&token=e6287bf2-2020-47aa-9fd3-f9fa60b360b5)

```python
from collections import deque
class Solution:
    def maxProfit(self, prices: List[int])-> int:
        stack = deque()
        profit = 0
        
        for price in prices:
            maxprice = 0
            while stack and price > stack[-1]:
                maxprice = max(maxprice, price - stack.pop())
            profit += maxprice
            stack.append(price)
        
        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://kseb0.gitbook.io/whiteboard/arrays-and-strings/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.
