BackmediumGreedyuncategorizedmedium

Optimal Storage Allocation Solution

Problem Statement

You are managing a logistics warehouse with a linear array of storage bins, each having a fixed maximum capacity. You are given an array capacities where capacities[i] denotes the maximum number of units the i-th bin can hold, and an integer totalSupplies representing the total volume of goods available for storage.

Your task is to determine the maximum number of supplies that can be successfully stored in the bins. The storage process must respect the individual capacity limits of each bin; you cannot exceed the capacity of any single bin. If the total available supplies exceed the combined capacity of all bins, you must store as much as possible until all bins are full. If the total supplies are less than or equal to the combined capacity, you can store all supplies.

Return the integer value representing the maximum number of units stored.

Example 1
Input
capacities = [5, 10, 15], totalSupplies = 20
Output
20

Explanation: The combined capacity of all bins is 5 + 10 + 15 = 30. Since the total supplies (20) are less than the combined capacity (30), all 20 units can be stored without exceeding any individual bin's limit. Thus, the answer is 20.

Example 2
Input
capacities = [3, 7, 2], totalSupplies = 15
Output
12

Explanation: The combined capacity is 3 + 7 + 2 = 12. The total supplies (15) exceed the combined capacity. Therefore, the maximum number of units that can be stored is limited by the total capacity of the bins, which is 12.

Example 3
Input
capacities = [100, 200, 300], totalSupplies = 500
Output
500

Explanation: The combined capacity is 100 + 200 + 300 = 600. Since 500 <= 600, all 500 units of supplies can be accommodated within the bins' capacities. The result is 500.

Example 4
Input
capacities = [1, 1, 1], totalSupplies = 5
Output
3

Explanation: The combined capacity is 1 + 1 + 1 = 3. The total supplies (5) are greater than the combined capacity. Hence, only 3 units can be stored, filling each bin to its maximum capacity of 1.

Constraints

  • 1 <= capacities.length <= 10^5
  • 1 <= capacities[i] <= 10^9
  • 1 <= totalSupplies <= 10^14
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Optimal Storage Allocation — Problem Statement & Solution Guide

GreedyMediumMixed
TimeO(n log n)
|
SpaceO(1)

Problem Description

You are managing a logistics warehouse with a linear array of storage bins, each having a fixed maximum capacity. You are given an array capacities where capacities[i] denotes the maximum number of units the i-th bin can hold, and an integer totalSupplies representing the total volume of goods available for storage.

Your task is to determine the maximum number of supplies that can be successfully stored in the bins. The storage process must respect the individual capacity limits of each bin; you cannot exceed the capacity of any single bin. If the total available supplies exceed the combined capacity of all bins, you must store as much as possible until all bins are full. If the total supplies are less than or equal to the combined capacity, you can store all supplies.

Return the integer value representing the maximum number of units stored.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Optimal Storage Allocation"

medium

WHY DOES IT MATTER?

Greedy with sorting is essential because it transforms a combinatorial selection problem into a deterministic linear pass after sorting, guaranteeing optimality while keeping the algorithm simple and efficient.

OPTIMIZATION CHALLENGE

The key insight is that the greedy choice (filling the smallest bin) is independent of future decisions; once a bin is filled, the remaining supplies are unaffected by the order of the remaining bins. This reduces the problem from exponential to O(n log n).

REAL-WORLD CONNECTION

Imagine a warehouse manager who wants to ship as many full pallets as possible with a limited number of boxes. By always packing the smallest pallets first, the manager maximizes the number of pallets shipped, analogous to filling the smallest bins first in the algorithm.

During an interview, emphasize that the greedy choice property is the linchpin: prove that filling the smallest bin first cannot hurt the optimal solution, and then show that sorting is the only overhead needed.

COMPLEXITY AT A GLANCE

⏱ Time:O(n log n)
💾 Space:O(1)

Core Theory — Why This Approach?

The problem reduces to a classic greedy selection: to maximize the number of bins that can be completely filled, we should always try to fill the smallest bins first. This ensures that we use the available supplies in the most efficient way, leaving as many supplies as possible to fill additional bins. A naive approach that tries all subsets of bins would have exponential time complexity and is infeasible for large inputs. Sorting the capacities array in ascending order and then iterating through it while subtracting each capacity from the remaining supplies gives an optimal solution in O(n log n) time, where n is the number of bins. The greedy choice property holds because once a bin is filled, the remaining supplies are independent of the order in which the remaining bins are considered; filling a larger bin first can only reduce the number of bins that can be filled.

The underlying algorithmic paradigm is *greedy with sorting*. The key insight is that the decision to fill a particular bin does not affect the feasibility of filling smaller bins later, so we can make the locally optimal choice (fill the smallest bin) and still guarantee a globally optimal solution. This pattern is common in resource allocation problems where the goal is to maximize the count of fully utilized resources.

By contrast, a naive approach that simply iterates over the bins in their original order may leave large bins partially filled while smaller bins remain unused, leading to a suboptimal count. Sorting ensures that we always consider the most “cost‑effective” bins first, thereby avoiding wasted supplies and guaranteeing optimality.

Interview Questions on This Problem

Q1At Google, how would you explain the greedy strategy used to maximize the number of fully filled bins, and why sorting is essential?

I would say that the greedy strategy is to always fill the smallest bin first because it consumes the least supplies, allowing us to potentially fill more bins. Sorting the capacities array in ascending order guarantees that we consider bins in the order of increasing cost, which is critical for the greedy choice property to hold. Without sorting, we might fill a large bin first and miss the chance to fill several smaller ones, reducing the overall count.

Q2A fintech startup asks: can we solve this problem in linear time without sorting?

In general, no. The problem requires us to consider bins in order of increasing capacity to ensure optimality. Without sorting, we would need to examine all subsets or use a priority queue, which still leads to O(n log n) or worse. However, if the capacities are bounded by a small constant, we could use counting sort to achieve linear time, but that’s a special case.

Q3During a high‑growth engineering interview, you’re asked to discuss space optimization. How would you reduce auxiliary space?

We can sort the array in place using an efficient in‑place algorithm like quicksort or introsort, which uses O(log n) stack space. If we’re allowed to modify the input, we can avoid any additional data structures. If the input must remain unchanged, we can copy the array, which costs O(n) space, but that’s the minimal overhead for sorting.

Examples

Example 1

Input

capacities = [5, 10, 15], totalSupplies = 20

Output

20

Explanation: The combined capacity of all bins is 5 + 10 + 15 = 30. Since the total supplies (20) are less than the combined capacity (30), all 20 units can be stored without exceeding any individual bin's limit. Thus, the answer is 20.

Example 2

Input

capacities = [3, 7, 2], totalSupplies = 15

Output

12

Explanation: The combined capacity is 3 + 7 + 2 = 12. The total supplies (15) exceed the combined capacity. Therefore, the maximum number of units that can be stored is limited by the total capacity of the bins, which is 12.

Example 3

Input

capacities = [100, 200, 300], totalSupplies = 500

Output

500

Explanation: The combined capacity is 100 + 200 + 300 = 600. Since 500 <= 600, all 500 units of supplies can be accommodated within the bins' capacities. The result is 500.

Example 4

Input

capacities = [1, 1, 1], totalSupplies = 5

Output

3

Explanation: The combined capacity is 1 + 1 + 1 = 3. The total supplies (5) are greater than the combined capacity. Hence, only 3 units can be stored, filling each bin to its maximum capacity of 1.

Constraints

  • 1 <= capacities.length <= 10^5
  • 1 <= capacities[i] <= 10^9
  • 1 <= totalSupplies <= 10^14

Optimal Approach & Strategy

Sort the capacities ascending, then iterate subtracting each capacity from the remaining supplies until you can’t fill the next bin. The number of bins processed before the loop stops is the maximum number of fully filled bins.

Brute Force Approach

Try every possible subset of bins and check if the total capacity of that subset is less than or equal to the supplies. Count the subsets that satisfy this and pick the one with the most bins. This is exponential in the number of bins.

Verified Code Solutions

JavaScript Solution
Time: O(n log n)
/**
 * @param {number[]} capacities
 * @param {number} totalSupplies
 * @return {number}
 */
var optimalStorageAllocation = function(capacities, totalSupplies) {
    const totalCapacity = capacities.reduce((sum, cap) => sum + cap, 0);
    return Math.min(totalCapacity, totalSupplies);
};

Asked in Top Tech Interviews

uncategorizedmediumnone

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.