3861. Minimum Capacity Box
Description
You are given an integer array capacity, where capacity[i] represents the capacity of the ith box, and an integer itemSize representing the size of an item.
The ith box can store the item if capacity[i] >= itemSize.
Return an integer denoting the index of the box with the minimum capacity that can store the item. If multiple such boxes exist, return the smallest index.
If no box can store the item, return -1.
Β
Example 1:
Input: capacity = [1,5,3,7], itemSize = 3
Output: 2
Explanation:
The box at index 2 has a capacity of 3, which is the minimum capacity that can store the item. Thus, the answer is 2.
Example 2:
Input: capacity = [3,5,4,3], itemSize = 2
Output: 0
Explanation:
The minimum capacity that can store the item is 3, and it appears at indices 0 and 3. Thus, the answer is 0.
Example 3:
Input: capacity = [4], itemSize = 5
Output: -1
Explanation:
No box has enough capacity to store the item, so the answer is -1.
Β
Constraints:
1 <= capacity.length <= 1001 <= capacity[i] <= 1001 <= itemSize <= 100
Solutions
Solution 1: Single Pass
We initialize a variable \(\textit{ans}\) to represent the index of the box with the smallest capacity that can hold the item, with an initial value of \(-1\). We iterate over the array \(\textit{capacity}\), and for each box, if its capacity is greater than or equal to \(\textit{itemSize}\), it can hold the item. At this point, we check whether it is the smallest-capacity box found so far; if so, we update \(\textit{ans}\). Finally, we return \(\textit{ans}\).
The time complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{capacity}\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 | |
1 2 3 4 5 6 7 8 9 10 11 12 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 | |
1 2 3 4 5 6 7 8 9 | |
1 2 3 4 5 6 7 8 9 10 | |