> ## Documentation Index
> Fetch the complete documentation index at: https://leetcode-py.wisl.dev/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> leetcode-py is a Python LeetCode practice environment generator with one CLI: lcpy. It is not a service or platform.
> Each problem is a directory under leetcode/ with README.md, solution.py, test_solution.py, helpers.py, and playground.ipynb. lcpy gen creates them from JSON templates bundled with the package.
> Examples are backed by tests; copy them verbatim.

# Best Time to Buy and Sell Stock IV

> Tested Python solution for LeetCode 188 with 24 pytest cases. Generate a practice environment with lcpy.

LeetCode 188, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [Dynamic Programming](/catalog/topics/dynamic-programming). [View on LeetCode](https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv/description/).

Generate this problem as a practice environment: tested reference solution, 24 [parametrized pytest cases](/practice/testing), and a playground notebook:

```bash theme={"theme":{"light":"github-light","dark":"github-dark"}}
lcpy gen -n 188   # by problem number
lcpy gen -s best_time_to_buy_and_sell_stock_iv   # by problem name
```

## Problem

You are given an integer array `prices` where `prices[i]` is the price of a given stock on the `i^th` day, and an integer `k`.

Find the maximum profit you can achieve. You may complete at most `k` transactions: i.e. you may buy at most `k` times and sell at most `k` times.

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

### Examples

```
Input: k = 2, prices = [2,4,1]
Output: 2
```

**Explanation:** Buy on day 1 (price = 2) and sell on day 2 (price = 4), profit = 4-2 = 2.

```
Input: k = 2, prices = [3,2,6,5,0,3]
Output: 7
```

**Explanation:** Buy on day 2 (price = 2) and sell on day 3 (price = 6), profit = 6-2 = 4. Then buy on day 5 (price = 0) and sell on day 6 (price = 3), profit = 3-0 = 3. Total profit is 4 + 3 = 7.

### Constraints

* 1 \<= k \<= 100
* 1 \<= prices.length \<= 1000
* 0 \<= prices\[i] \<= 1000

## Solution

Reference implementation from [solution.py on GitHub](https://github.com/wislertt/leetcode-py/blob/main/leetcode/best_time_to_buy_and_sell_stock_iv/solution.py), full suite in [test\_solution.py](https://github.com/wislertt/leetcode-py/blob/main/leetcode/best_time_to_buy_and_sell_stock_iv/test_solution.py):

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n * min(k, n // 2))
    # Space: O(min(k, n // 2))
    def max_profit(self, k: int, prices: list[int]) -> int:
        n = len(prices)
        if n == 0:
            return 0
        # Each transaction uses at least two days, so more trades than n // 2
        # degenerate into the unlimited-transaction case.
        limit = min(k, n // 2)
        buy = [-(10**9)] * (limit + 1)
        sell = [0] * (limit + 1)
        for price in prices:
            for j in range(1, limit + 1):
                buy[j] = max(buy[j], sell[j - 1] - price)
                sell[j] = max(sell[j], buy[j] + price)
        return sell[limit]
```

## Complexity

| Time | Space |
| - | - |
| O(n \* min(k, n // 2)) | O(min(k, n // 2)) |

## Tags


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.