Solution: Put Marbles in Bags
Let’s solve the Put Marbles in Bags problems using the Sort and Search pattern.
We'll cover the following
Statement
You are given k
bags and a 0-indexed integer array, weights
, where weights[i]
represents the weight of the
Your task is to divide the marbles into the k
bags according to the following rules:
No bag can be empty.
If the
marble and the marble are placed in the same bag, then all marbles with indexes between i
andj
(inclusive) must also be placed in that same bag.If a bag contains all the marbles from index
i
toj
(inclusive), its cost is calculated asweights[i] + weights[j]
.
After distributing the marbles, the sum of the costs of all the k
bags is called the score.
Return the difference between the maximum and minimum scores achievable by distributing the marbles into the k
bags.
Constraints:
k
weights.length
weights[i]
Solution
The main idea is to split the weights array into k
bags by making k - 1
cuts between marbles. To do this efficiently, we use the sort and search pattern, which helps us quickly identify the best positions to split for both maximum and minimum scores. The key observation is that when we make a cut between two marbles, the marble before the cut becomes the end of one bag, and the marble after the cut becomes the start of the next bag. So, every cut adds two boundary marbles that affect the total score, because each bag’s score is the sum of its first and last marble, and we can include these boundary marbles in the final sum of all the scores.
Note: A cut between marble
and means marble ends one bag, and marble starts the next; their sum contributes to the total score.
The first and last marbles of the entire array are always part of the score, so the only part that changes with different splits is the contribution from the cuts. To capture these, we calculate the sum of each pair of adjacent marbles in the array. Then, we iterate through the array from the
Example: If the weights are
[1, 3, 5, 2]
, we get the pairwise sums:[(1 + 3 = 4), (3 + 5 = 8), (5 + 2 = 7)]
These pairwise sums represent the potential score impact of placing a cut at that position. By sorting these sums, we can easily pick the k - 1
largest to get the maximum score, and the k - 1
smallest to get the minimum score. The final answer is the difference between these two totals.
Now, let’s look at the solution steps below:
If
k
is, all marbles must be placed in a single bag. This case has no partitioning; the difference between the maximum and minimum scores is 0
, so we return0
.Otherwise, we calculate the initial cost of a single bag containing all marbles by summing the first and last weights in the array. We do this by
initialCost
=weights[0]
+weights[n-1]
.Then, we compute the pairwise sums of all adjacent marbles. For each index
i
from0
ton - 2
(wheren
is the length ofweights
), we calculateweights[i] + weights[i + 1]
and store it inpairwiseSums
.Next, we sort the
pairwiseSums
list in ascending order. This allows us to efficiently access the smallest and largest values needed for calculating the minimum and maximum scores.To calculate the maximum score:
We take the largest
(k - 1)
values from the end of the sorted pairwise sums list usingpairwiseSums[-(k - 1):]
, and add their sum toinitialCost
. After calculating, we store the result inmaxScore
.
To calculate the minimum score:
Similar to what we did for the maximum score, we take the smallest
(k - 1)
values from the beginning of the sorted pairwise sums list usingpairwiseSums[:k - 1]
, and add their sum toinitialCost
. After calculating, we store the result inminScore
.
Finally, we return the difference between the maximum and minimum scores using
maxScore - minScore
.
Let’s look at the following illustration to get a better understanding of the solution:
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.