Problem Description
Given an array of marbles' weights and an integer k representing the number of bags, partition the array into k contiguous subarrays (bags) such that no bag is empty. The cost of a bag that covers indices i through j is defined as weights[i] + weights[j]. The total score is the sum of the costs of all bags. Return the difference between the maximum and minimum possible total scores achievable by different valid distributions.
Key Insights
- The first and last weights always contribute to the cost since the first bag starts with weights[0] and the last bag ends with weights[n-1].
- Any additional bag creation requires making a cut between marbles; a cut between indices i and i+1 adds an extra cost weights[i] + weights[i+1].
- To minimize the total score, one should choose the k-1 cuts with the smallest additional costs; conversely, to maximize the total score, choose the k-1 largest additional costs.
- The problem reduces to computing candidate values for cuts (for every adjacent pair) and then picking the smallest and largest sums appropriately.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting the candidate costs computed from the adjacent pairs. Space Complexity: O(n) for storing the candidate values.
Solution
We first compute a base cost using the first and last elements (weights[0] + weights[n-1]), which is included in every valid partition. For each possible cut between marbles (from index 0 to n-2), we calculate an additional candidate cost = weights[i] + weights[i+1]. These candidates represent the extra cost that would get added if we choose that particular cut to separate a bag.
Since we need to create exactly k bags, we have to make exactly k-1 cuts. The minimal configuration is achieved by selecting the k-1 smallest candidate costs, while the maximum configuration is achieved by selecting the k-1 largest candidate costs. We then sum these chosen candidate costs with the base cost. The final answer is the difference between the maximum total score and the minimum total score.
The algorithm uses a greedy approach and a sorting step to pick the appropriate candidate cuts.