Magicsheet logo

Put Marbles in Bags

Hard
61%
Updated 6/1/2025

Put Marbles in Bags

What is this problem about?

The Put Marbles in Bags problem asks you to distribute marbles into k bags such that the cost (sum of first + last marble in each bag) is maximized or minimized. The difference between maximum and minimum cost is the answer. This hard coding problem has an elegant key insight: only the split points between bags matter. The array, sorting, heap, and greedy interview pattern is fully tested.

Why is this asked in interviews?

Uber, Microsoft, Meta, Amazon, TikTok, and Google ask this because the reduction — from "distribute into k bags" to "pick k-1 split points" — is non-obvious. Once you see it, sorting the pair sums at split points gives the answer in O(n log n).

Algorithmic pattern used

Split-point reduction + sort. Key insight: the cost for any distribution equals marbles[0] + marbles[n-1] (always included) plus the sum of marbles[i] + marbles[i+1] for each chosen split between index i and i+1. There are n-1 possible split points; you choose k-1 of them. To maximize cost: pick largest k-1 pair sums. To minimize: pick smallest k-1 pair sums. Answer = sum of largest k-1 - sum of smallest k-1.

Example explanation

marbles=[1,3,5,1], k=2. Pair sums at splits: [1+3=4, 3+5=8, 5+1=6]. Base = 1+1=2. Choose 1 split (k-1=1). Max split: pick 8. Max cost = 2+8=10. Min split: pick 4. Min cost = 2+4=6. Answer = 10-6 = 4.

Common mistakes candidates make

  • Simulating all possible bag distributions (exponential).
  • Not recognizing that base cost (first+last marble) is constant.
  • Off-by-one: need k-1 split points, not k.
  • Sorting the whole array instead of the pair sums.

Interview preparation tip

Put Marbles in Bags demonstrates a powerful reduction: "k groups" → "k-1 split choices." This reduction appears in many interval and partitioning problems. Once you identify the invariant (first+last are always included), the problem reduces to choosing from n-1 candidates. Sorting these candidates and summing the top/bottom k-1 gives the answer in O(n log n).

Similar Questions