Minimum Cost to Merge Stones

HardDynamic Programminginterval dp

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

stones[i] is the number of stones in pile i, and the piles stand in a row. One move merges **exactly k consecutive** piles into a single pile whose size is their total; that move costs the same total. Return the minimum total cost to end with a single pile. If it is impossible to reach exactly one pile, return -1. If there is already a single pile, the cost is 0.

Examples

Input: stones = [3,2,4,1], k = 2
Output: 20
Merge [3,2] (5) -> [5,4,1]; merge [4,1] (5) -> [5,5]; merge [5,5] (10). Total 20.
Input: stones = [3,2,4,1], k = 3
Output: -1
Each move removes 2 piles, so 4 piles can never become 1.
Input: stones = [3,5,1,2,6], k = 3
Output: 25
Merge [5,1,2] (8) -> [3,8,6]; merge all (17). Total 25.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More interval dp problems