LeetCode 2551: Put Marbles in Bags Solution

Master LeetCode problem 2551 (Put Marbles in Bags), a hard challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

2551. Put Marbles in Bags

Problem 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.

:

Solution Code

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

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 2551 (Put Marbles in Bags)?

This page provides optimized solutions for LeetCode problem 2551 (Put Marbles in Bags) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 2551 (Put Marbles in Bags)?

The time complexity for LeetCode 2551 (Put Marbles in Bags) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 2551 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 2551 in Java, C++, or Python.

Back to LeetCode Solutions