Taro Logo

Minimized Maximum of Products Distributed to Any Store #1 Most Asked

Medium
9 views
Topics:
ArraysBinary Search

You are given an integer n indicating there are n specialty retail stores. There are m product types of varying amounts, which are given as a 0-indexed integer array quantities, where quantities[i] represents the number of products of the ith product type.

You need to distribute all products to the retail stores following these rules:

  • A store can only be given at most one product type but can be given any amount of it.
  • After distribution, each store will have been given some number of products (possibly 0). Let x represent the maximum number of products given to any store. You want x to be as small as possible, i.e., you want to minimize the maximum number of products that are given to any store.

Return the minimum possible x.

Example 1:

Input: n = 6, quantities = [11,6]
Output: 3
Explanation: One optimal way is:
- The 11 products of type 0 are distributed to the first four stores in these amounts: 2, 3, 3, 3
- The 6 products of type 1 are distributed to the other two stores in these amounts: 3, 3
The maximum number of products given to any store is max(2, 3, 3, 3, 3, 3) = 3.

Example 2:

Input: n = 7, quantities = [15,10,10]
Output: 5
Explanation: One optimal way is:
- The 15 products of type 0 are distributed to the first three stores in these amounts: 5, 5, 5
- The 10 products of type 1 are distributed to the next two stores in these amounts: 5, 5
- The 10 products of type 2 are distributed to the last two stores in these amounts: 5, 5
The maximum number of products given to any store is max(5, 5, 5, 5, 5, 5, 5) = 5.

Example 3:

Input: n = 1, quantities = [100000]
Output: 100000
Explanation: The only optimal way is:
- The 100000 products of type 0 are distributed to the only store.
The maximum number of products given to any store is max(100000) = 100000.

Constraints:

  • m == quantities.length
  • 1 <= m <= n <= 105
  • 1 <= quantities[i] <= 105

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the maximum possible values for the number of stores and the quantity of each product? Are these values within the range of standard integer data types?
  2. Can the input array of product quantities contain zero values, and if so, is it valid to distribute zero products to a store?
  3. If it's impossible to distribute all products given a particular maximum product distribution, what should the function return? Should I return -1, throw an exception, or is there a specific error code?
  4. Is the number of stores guaranteed to be less than or equal to the total number of products available?
  5. If multiple 'minimized maximum' values exist, should I return any one of them, or is there a specific one that must be returned (e.g., the smallest such value)?

Brute Force Solution

Approach

The brute force approach aims to find the smallest possible maximum number of products any store receives. To achieve this, we try every possible value for this maximum, checking each time if it is feasible to distribute all products to the stores while adhering to that maximum.

Here's how the algorithm would work step-by-step:

  1. Start by guessing the maximum number of products a store could receive. Begin with a low guess and increase it gradually.
  2. For each guess of the maximum, try to distribute the products to the stores. Start with the first product type and see how many stores can receive that type, based on the maximum you guessed.
  3. Continue distributing each product type to as many stores as possible, always making sure no store receives more than your guessed maximum number of products total.
  4. If you are able to distribute all product types to all stores without exceeding the maximum for any store, then your guess was feasible. Store this maximum value as the best so far.
  5. If at any point you can't distribute a product type because all stores are already at their maximum, then your guess was too low. Increase your guess and repeat the process from step two.
  6. Keep trying different maximum values until you find the smallest one that allows you to distribute all the product types to all stores.

Code Implementation

def find_minimized_maximum(number_of_products, number_of_stores):
    low_guess = 1
    high_guess = max(number_of_products)
    best_maximum = high_guess

    while low_guess <= high_guess:
        maximum_products_per_store = (low_guess + high_guess) // 2

        if is_feasible(number_of_products, number_of_stores, maximum_products_per_store):
            # If feasible, try to reduce the maximum
            best_maximum = maximum_products_per_store
            high_guess = maximum_products_per_store - 1
        else:
            # If not feasible, increase the maximum
            low_guess = maximum_products_per_store + 1

    return best_maximum

def is_feasible(number_of_products, number_of_stores, maximum_products_per_store):
    stores_available = number_of_stores

    for product_quantity in number_of_products:
        number_of_stores_needed = (product_quantity + maximum_products_per_store - 1) // maximum_products_per_store

        #If we don't have enough stores to handle product
        if number_of_stores_needed > stores_available:
            return False
        
        stores_available -= number_of_stores_needed

    return True

Big(O) Analysis

Time Complexity
O(m * n * log(max_products))The brute force approach iterates through possible maximum values, performing a feasibility check for each. The maximum possible product value (max_products) influences the upper bound of the search, resulting in a logarithmic factor due to the binary search-like nature of finding the minimum maximum (log(max_products)). For each maximum value, we iterate through all 'm' product types. Within each product type, we potentially iterate through all 'n' stores to distribute the products. Therefore, the overall time complexity is O(m * n * log(max_products)).
Space Complexity
O(1)The brute force approach described primarily involves iterative guessing and checking feasibility. It does not explicitly mention the creation of any auxiliary data structures like arrays, hash maps, or lists to store intermediate results or track visited states. The algorithm operates in place, adjusting the 'guess' variable. Therefore, the space complexity is constant, irrespective of the input size (number of products or stores).

Optimal Solution

Approach

The goal is to minimize the largest number of products any single store receives. To do this efficiently, we'll use a strategy that narrows down the possibilities by repeatedly guessing and checking if a certain maximum distribution is possible, adjusting our guess each time to get closer to the optimal solution.

Here's how the algorithm would work step-by-step:

  1. First, determine the range of possible values for the maximum number of products a store can receive. The lowest possible value is 1, and the highest possible value is the largest quantity of products available.
  2. Pick a value in the middle of that range and act as if it's the maximum that any store can receive. We are basically guessing a potential answer.
  3. Determine the number of stores we can supply for each product type, given this maximum. A product type can only supply to as many stores as its quantity allows, divided by our guessed maximum.
  4. Sum up the total number of stores that can be supplied across all product types using our guessed maximum.
  5. If the total number of stores we can supply is greater than or equal to the actual number of stores, this means our guessed maximum is potentially too high. We can safely try a lower guess.
  6. If the total number of stores we can supply is less than the actual number of stores, this means our guessed maximum is too low. We must try a higher guess.
  7. Repeat the guessing and checking process, narrowing the range of possible values each time. Eventually, we will converge on the smallest possible maximum that still allows us to supply all the stores. This is our answer.

Code Implementation

def minimized_maximum_of_products_distributed_to_any_store(number_of_products, number_of_stores):
    low = 1
    high = max(number_of_products)

    while low <= high:
        mid = (low + high) // 2

        # Calculate total stores supplied with the guessed maximum.
        stores_supplied = 0
        for product_quantity in number_of_products:
            stores_supplied += product_quantity // mid

        # Adjust search range based on stores supplied.
        if stores_supplied >= number_of_stores:
            high = mid - 1
        else:
            low = mid + 1

    # 'low' is the minimized maximum.
    return low

Big(O) Analysis

Time Complexity
O(n log m)The algorithm employs a binary search approach to find the minimized maximum, where m represents the largest product quantity among the given products. Within each binary search iteration, we iterate through the array of product quantities (n products) to determine how many stores each product type can supply, given the current maximum. This inner loop takes O(n) time. Since binary search takes O(log m) time where m is the range (maximum quantity), the overall time complexity is O(n log m).
Space Complexity
O(1)The algorithm described performs a binary search and only uses a few variables to store the low and high bounds of the search space, the middle value being tested, and a running sum of the number of stores that can be supplied. No additional data structures that scale with the input (the quantities of products or the number of stores) are used. Therefore, the auxiliary space required remains constant regardless of the input size, resulting in O(1) space complexity.

Edge Cases

Empty products array
How to Handle:
Return 0 since no products can be distributed.
Stores is zero or negative
How to Handle:
Return 0 as no distribution is possible with no or negative stores.
Single product and single store
How to Handle:
Return the product's quantity directly, as it's the only possible maximum.
All products have quantity of 1
How to Handle:
The maximum will be 1 if stores >= number of products, otherwise, the minimum max will be ceil(num_products/stores).
One very large product quantity compared to others
How to Handle:
Binary search handles large number ranges; the algorithm effectively searches for the optimum value.
Integer overflow during calculations
How to Handle:
Use long type for calculations to prevent potential integer overflows.
Stores value exceeds the number of products
How to Handle:
Binary search will still correctly converge because the lower bound for the maximum product is 1.
Products array contains very large numbers of products
How to Handle:
The Binary Search should still work as it looks for the minimum maximum number, provided no int overflow errors.
0/0 completed