> ## 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.

# Minimum Cost to Merge Stones Python Solution

> Tested Python solution for LeetCode 1000 with 18 pytest cases. Generate a practice environment with lcpy.

LeetCode 1000, [Hard](/catalog/hard). Topics: [Array](/catalog/topics/array), [Dynamic Programming](/catalog/topics/dynamic-programming), [Prefix Sum](/catalog/topics/prefix-sum). [View on LeetCode](https://leetcode.com/problems/minimum-cost-to-merge-stones/description/).

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

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

## Problem

There are `n` piles of stones arranged in a row. The `i^th` pile has `stones[i]` stones.

A move consists of merging exactly `k` **consecutive** piles into one pile, and the cost of this move is equal to the total number of stones in these `k` piles.

Return the minimum cost to merge all piles of stones into one pile. If it is impossible, return `-1`.

### Examples

```
Input: stones = [3,2,4,1], k = 2
Output: 20
```

**Explanation:** We start with \[3, 2, 4, 1].
We merge \[3, 2] for a cost of 5, and we are left with \[5, 4, 1].
We merge \[4, 1] for a cost of 5, and we are left with \[5, 5].
We merge \[5, 5] for a cost of 10, and we are left with \[10].
The total cost was 20, and this is the minimum possible.

```
Input: stones = [3,2,4,1], k = 3
Output: -1
```

**Explanation:** After any merge operation, there are 2 piles left, and we can't merge anymore. So the task is impossible.

```
Input: stones = [3,5,1,2,6], k = 3
Output: 25
```

**Explanation:** We start with \[3, 5, 1, 2, 6].
We merge \[5, 1, 2] for a cost of 8, and we are left with \[3, 8, 6].
We merge \[3, 8, 6] for a cost of 17, and we are left with \[17].
The total cost was 25, and this is the minimum possible.

### Constraints

* `n == stones.length`
* `1 <= n <= 30`
* `1 <= stones[i] <= 100`
* `2 <= k <= 30`

## Solution

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

```python theme={"theme":{"light":"github-light","dark":"github-dark"}}
class Solution:
    # Time: O(n^3 / k * k) = O(n^3) over intervals with k-step splits
    # Space: O(n^2)
    def merge_stones(self, stones: list[int], k: int) -> int:
        n = len(stones)
        if n == 1:
            return 0
        if (n - 1) % (k - 1) != 0:
            return -1

        prefix = [0] * (n + 1)
        for i, stones_count in enumerate(stones):
            prefix[i + 1] = prefix[i] + stones_count

        # dp[i][j] = min cost to merge stones[i..j] down to the minimum possible pile count
        dp = [[0] * n for _ in range(n)]
        for length in range(k, n + 1):
            for i in range(n - length + 1):
                j = i + length - 1
                dp[i][j] = min(dp[i][mid] + dp[mid + 1][j] for mid in range(i, j, k - 1))
                if (j - i) % (k - 1) == 0:
                    dp[i][j] += prefix[j + 1] - prefix[i]
        return dp[0][n - 1]
```

## Complexity

| Time | Space |
| - | - |
| O(n^3 / k \* k) = O(n^3) over intervals with k-step splits | O(n^2) |

## Tags


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