Minimize the Cost of Merging Exactly K Adjacent Piles at a Time

Quick Overview

Minimize the Cost of Merging Exactly K Adjacent Piles at a Time. Piles in stones remain in row order.

Minimize the Cost of Merging Exactly K Adjacent Piles at a Time

Company: Amazon

Role: Software Engineer

Category: Coding & Algorithms

Difficulty: hard

Interview Round: Other

### Problem Piles in `stones` remain in row order. Each move merges exactly k consecutive current piles into one and costs their combined stone count. Return the minimum cost of obtaining one pile, or-1 if that is impossible. ```cpp class Solution { public: int mergeStones(vector<int>& stones, int k); }; ``` ### Examples **Example 1:** ```text Input: stones = [1,2,3], k = 2 Output: 9 Explanation: Merge1 and2 for3, then merge the resulting3 with the last3 for6. The other first merge costs5+6=11. ``` **Example 2:** ```text Input: stones = [2,2,2,2,2], k = 3 Output: 16 Explanation: Any first triple costs6 and leaves three piles totaling10; their final merge costs10, for16. ``` ### Constraints - `n == stones.length`; `1 <= n <= 30`. - `1 <= stones[i] <= 100`. - `2 <= k <= 30`. ### Contract considerations Only consecutive current piles may merge. The required output is the minimum total cost, not a merge sequence. ```hint Read the boundary condition An interval reduced to p piles is a useful state because the final merge always requires exactly k piles. ``` ### Boundary reminders Only consecutive current piles may merge. The required output is the minimum total cost, not a merge sequence.

Overview: Minimize the Cost of Merging Exactly K Adjacent Piles at a Time. Piles in stones remain in row order.

Amazon logo
Amazon
Jun 21, 2026
hardSoftware EngineerOtherCoding & Algorithms
0
0

Problem

Piles in stones remain in row order. Each move merges exactly k consecutive current piles into one and costs their combined stone count. Return the minimum cost of obtaining one pile, or-1 if that is impossible.

class Solution {
public:
    int mergeStones(vector<int>& stones, int k);
};

Examples

Example 1:

Input: stones = [1,2,3], k = 2
Output: 9
Explanation: Merge1 and2 for3, then merge the resulting3 with the last3 for6. The other first merge costs5+6=11.

Example 2:

Input: stones = [2,2,2,2,2], k = 3
Output: 16
Explanation: Any first triple costs6 and leaves three piles totaling10; their final merge costs10, for16.

Constraints

  • n == stones.length ; 1 <= n <= 30 .
  • 1 <= stones[i] <= 100 .
  • 2 <= k <= 30 .

Contract considerations

Only consecutive current piles may merge. The required output is the minimum total cost, not a merge sequence.

Boundary reminders

Only consecutive current piles may merge. The required output is the minimum total cost, not a merge sequence.