Sign in with Google

Google will share your name, email, and profile picture with DevExCode. See our privacy policy.

LeetCode 2551: Put Marbles in Bags

LeetCode 2551 Solution Explanation

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.

  1. Algorithm:

    • We start by initializing two variables low and high where low is the minimum possible score (sum of all weights) and high 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.
  2. 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.
  3. Space Complexity:

    • The space complexity of this approach is O(1) as we are using a constant amount of extra space.

:

LeetCode 2551 Solutions in Java, C++, Python

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;
    }
}

Interactive Code Editor for LeetCode 2551

Improve Your LeetCode 2551 Solution

Use the editor below to refine the provided solution for LeetCode 2551. Select a programming language and try the following:

  • Add import statements if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.

Loading editor...

Related LeetCode Problems