Put Marbles In Bags

Solution For Put Marbles In Bags

The Put Marbles In Bags problem on Leetcode is a medium-level algorithm problem that requires you to divide a given number of marbles between the given number of bags in the most optimal manner. The problem statement demands you to maximize the minimum number of marbles in each bag.

Problem Statement:
You have a bag with marbles. You want to divide the marbles among several bags in such a way that the following conditions are met:

  • You are given an array of n integers, where arr[i] represents the number of marbles that should be put in the i-th bag.

  • There are m bags, numbered from 1 to m.

  • Each bag can hold arbitrarily many marbles, but the total number of marbles in all bags should be equal to the number of marbles in the original bag.

  • Find the maximum number of marbles you can put in any bag such that every bag has at least that many marbles.

Solution Approach:

This problem is similar to the classic binary search problem of finding the smallest element greater than the target element in a given array. By considering the number we can obtain a suitable lower limit and a suitable upper limit on each i-th bags. We can then use binary search to find the optimal solution in the search space between these limits.

To find the lower limit, we start with the first bag and assume we put all the marbles in it. This would be to maximize the minimum number of marbles in the bag, thus set it as the lower limit. We then proceed to the remaining bags and divide the remaining marbles equally, so that each bag would have the same number of marbles as the first bag- the lower limit we just found.

To find the upper limit, we add up all the marbles in the bags such that every bag has the same maximum value. We then divide this sum by the number of the bags. This result will give us the upper limit for all the bags since any bag that can hold more than this number will have more marbles than the maximum number of marbles in the bags.

Once we have found the upper and lower limits for all the bags, we can begin our binary search algorithm. We will iterate over the range between the lower and upper limits to find the values of the minimum number of marbles in each bag. We can then check if dividing the marbles in this way is a valid solution to the problem.

If the solution is valid, we can increase the lower limit to the mid value of the lower and upper limits, as this will guarantee that we have the maximum possible number of marbles in each bag. If the solution is invalid, we can decrease the upper limit to the mid value of the lower and upper limits.

We can repeat the binary search until we find the lowest solution.

Code Implementation:

Here is the sample code that implements the approach described above:

“`
class Solution {
public:
int minimumSize(vector& arr, int m) {
int n = arr.size();
long long s = 0;
for (int x: arr) s += x;

    int l = 1, r = s;
    while (l < r) {
        int mid = (l + r) / 2;

        int cnt = 0;
        long long sum = 0;
        for (int i = 0; i < n; ++i) {
            if (arr[i] > mid) {
                cnt = m + 1;
                break;
            }

            if (sum + arr[i] > mid) {
                ++cnt;
                sum = arr[i];
            } else {
                sum += arr[i];
            }
        }

        if (cnt < m) {
            r = mid;
        } else {
            l = mid + 1;
        }
    }

    return l;
}

};
“`

Conclusion:
The Put Marbles In Bags problem can be solved by using the binary search algorithm to find the maximum number of marbles that can be placed in any bag such that every bag has at least that many marbles. By implementing the approach described above, you can solve this problem and achieve the desired output.

Step by Step Implementation For Put Marbles In Bags

You can use any data structure you want.

/**
 * Given n marbles and m bags, find a way to put the marbles into the bags such that:

Each bag can only contain marbles of the same color
Each bag must contain at least one marble
The total number of marbles in each bag must be less than or equal to the capacity of the bag
Find the maximum number of bags that can be filled.

Example 1:

Input: n = 3, m = 2, capacity = [2,5]
Output: 2
Explanation: We can put 2 marbles in the first bag and 1 marble in the second bag.
Example 2:

Input: n = 7, m = 3, capacity = [4,5,6]
Output: 3
Explanation: We can put 3 marbles in bag 0, 2 marbles in bag 1 and 2 marbles in bag 2.
 */

import java.util.*;

class Solution {
    public int putMarblesInBags(int n, int m, int[] capacity) {
        // check for invalid inputs
        if (n <= 0 || m <= 0 || capacity == null || capacity.length != m) {
            return 0;
        }

        // sort the capacity array in ascending order
        Arrays.sort(capacity);

        // create a new array to store the number of marbles that can be put in each bag
        int[] marbles = new int[m];

        // put one marble in each bag
        for (int i = 0; i < m; i++) {
            marbles[i] = 1;
        }

        // try to put more marbles in each bag, starting from the bag with the smallest capacity
        for (int i = 0; i < m; i++) {
            // if there are marbles left to put in bags
            if (n > 0) {
                // try to put as many marbles as possible in the current bag
                int numMarbles = Math.min(n, capacity[i] - marbles[i]);
                marbles[i] += numMarbles;
                n -= numMarbles;
            }
        }

        // count the number of bags that are filled
        int count = 0;
        for (int i = 0; i < m; i++) {
            if (marbles[i] > 0) {
                count++;
            }
        }
        return count;
    }
}
def put_marbles_in_bags(n, k): 

# put marbles in bags 
# input: n marbles, k bags 
# output: minimum number of moves needed to put all marbles in k bags 

# keep track of the number of moves needed 
moves = 0 

# keep track of the number of marbles in each bag 
bag_marbles = [0] * k 

# put one marble in each bag to start 
for i in range(k): 
bag_marbles[i] += 1 
moves += 1 

# put marbles in bags until all marbles have been placed 
while n > k: 

# find the bag with the most marbles 
max_marbles = 0 
max_marbles_index = 0 
for i in range(k): 
if bag_marbles[i] > max_marbles: 
max_marbles = bag_marbles[i] 
max_marbles_index = i 

# put a marble in the bag with the most marbles 
bag_marbles[max_marbles_index] += 1 
moves += 1 
n -= 1 

# put the remaining marbles in the bags 
for i in range(k): 
if n > 0: 
bag_marbles[i] += 1 
moves += 1 
n -= 1 

# return the number of moves needed 
return moves
var putMarblesInBags = function(marbles, bags) {
    // your code here
};
int put_marbles_in_bags(int num_marbles, int num_bags) {
    // This is a C++ solution for the leetcode problem put-marbles-in-bags
    // Output should only consist of exact code with comments and nothing else
    
    // We first need to check if the input is valid
    if (num_marbles <= 0 || num_bags <= 0) {
        return -1;
    }
    
    // We will use a vector to store the number of marbles in each bag
    // We will also use a variable to keep track of the number of bags used
    vector bags;
    int num_used = 0;
    
    // We will start by putting as many marbles as possible in the first bag
    bags.push_back(num_marbles);
    num_used++;
    
    // We will then go through each bag and see if we can put any marbles in it
    for (int i = 0; i < num_used; i++) {
        // If the bag can hold more marbles, we will put marbles in it until it is full
        while (bags[i] < num_bags) {
            bags[i]++;
            num_marbles--;
            
            // If there are no more marbles left, we can break out of the loop
            if (num_marbles == 0) {
                break;
            }
        }
        
        // If there are marbles left and we have not reached the maximum number of bags, we will create a new bag
        if (num_marbles > 0 && num_used < num_bags) {
            bags.push_back(num_marbles);
            num_used++;
        }
    }
    
    // We will return the number of bags used
    return num_used;
}
public class Solution {
    public int PutMarblesInBags(int[] marbles, int bagCapacity) {
        // Check for invalid input
        if (marbles == null || marbles.Length == 0 || bagCapacity <= 0) {
            return 0;
        }
        
        // Sort the array in ascending order
        Array.Sort(marbles);
        
        // Initialize variables
        int numBags = 1;
        int currentCapacity = 0;
        
        // Iterate through each marble
        foreach (int marble in marbles) {
            // If the marble can fit in the current bag, add it
            if (currentCapacity + marble <= bagCapacity) {
                currentCapacity += marble;
            }
            // Otherwise, create a new bag and add the marble to it
            else {
                numBags++;
                currentCapacity = marble;
            }
        }
        
        return numBags;
    }
}


Scroll to Top
[gravityforms id="5" description="false" titla="false" ajax="true"]