LeetCode 2551: Put Marbles in Bags
Problem Description
Explanation:
To solve this problem, we need to distribute the marbles into k bags while minimizing the difference between the maximum and minimum scores among marble distributions. We will approach this problem using binary search and prefix sum techniques.
-
Algorithm:
- We start by initializing two variables
low
andhigh
wherelow
is the minimum possible score (sum of all weights) andhigh
is the maximum possible score (sum of maximum k weights). - Perform binary search in the range [low, high] to find the optimal score.
- In each binary search iteration, calculate the mid value and check if it's feasible to distribute the marbles such that the maximum bag cost is less than or equal to the mid value.
- If feasible, update the answer and move towards the left half, else move towards the right half.
- We start by initializing two variables
-
Time Complexity:
- The time complexity of this approach is O(n log(sum(weights))) where n is the number of marbles and sum(weights) represents the sum of all marble weights.
-
Space Complexity:
- The space complexity of this approach is O(1) as we are using a constant amount of extra space.
:
Solutions
class Solution {
public int minDifference(int[] weights, int k) {
Arrays.sort(weights);
int n = weights.length;
if (k >= n) return 0;
int low = Arrays.stream(weights).sum();
int high = Arrays.stream(weights).skip(n - k).sum();
int res = high - low;
for (int i = 0; i < k; i++) {
res = Math.min(res, high - low);
low += weights[i];
high += weights[n - k + i];
}
return res;
}
}
Loading editor...