Minimum Cost to Merge Stones
Updated
Problem statement
You are given an array stones, where stones[i] is the number of stones in pile i, and an integer k.
In one move, choose exactly k consecutive piles and merge them into one pile. The cost of the move is the total number of stones in those k piles.
Return the minimum total cost needed to merge all piles into one pile. Return -1 if it is impossible.
Function
mergeStones(stones: int[], k: int) → intExamples
Example 1
stones = [3,2,4,1]k = 2return = 20One optimal sequence is [3,2,4,1] -> [5,4,1] -> [5,5] -> [10], with total cost 5 + 5 + 10 = 20.
Example 2
stones = [3,2,4,1]k = 3return = -1Each move reduces the number of piles by two, so four piles cannot become exactly one pile.
Example 3
stones = [3,5,1,2,6]k = 3return = 25Merge [5,1,2] for cost 8, then merge [3,8,6] for cost 17.
Constraints
1 <= stones.length <= 30.1 <= stones[i] <= 100.2 <= k <= 30.
More Google Onsite Interview questions
- Route Pattern MatcherPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Evaluate a Nested Math ExpressionPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- Distinct Subset SumsONSITE INTERVIEW · Seen Nov 2026
- Playlist With No Same Artist in a RowONSITE INTERVIEW · Seen Nov 2026
- Delete Nodes and Return Forest RootsONSITE INTERVIEW · Seen Nov 2026
- Dice-Walk Winning ProbabilityPHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- First and Last Target Position in a Mountain ArrayONSITE INTERVIEW · Seen Nov 2026
- Lowest Common Ancestor in an N-ary TreePHONE SCREEN · ONSITE INTERVIEW · Seen Nov 2026
- 0/1 Knapsack with Weight and Volume LimitsONSITE INTERVIEW · Seen Nov 2026
- Batched Subsequence Word MatchesONSITE INTERVIEW · Seen Nov 2026
Similar questions at other companies
- Best Improvement Period of at Least K IntervalsAmazon · PHONE SCREEN
- Maximum Subarray SumCapital One · PHONE SCREEN · ONSITE INTERVIEWCapital One interview questions
- Minimum Variance Sum SplitAirbnb · PHONE SCREENAirbnb interview questions
- Largest All-One Square Area and CountNVIDIA · PHONE SCREENNVIDIA interview questions
- Maximum Non-Decreasing Array LengthVisa · OAVisa interview questions
- Maximize CollaborationTikTok · OATikTok interview questions
- Maximum Sum RectangleDeloitte · OADeloitte interview questions
- Maximum Game Score with Fixed Forward JumpsStripe · OAStripe interview questions
- Maximum Apples from Two Disjoint Fixed-Length SegmentsMarshall Wace · OAMarshall Wace interview questions
- Shortest Subarray with Sum at Least KOracle · ONSITE INTERVIEWOracle interview questions