_minimum number of umbrellas(DP)
_minimum number of umbrellas(DP)
You are tasked with determining the minimum number of umbrellas required to shelter a
given number of people exactly, using umbrellas of various sizes. If it is not possible to meet the
exact requirement using any combination of the available umbrella sizes, return -1.
Inputs:
Output:
● Return the minimum number of umbrellas needed to shelter exactly the given number
of people (requirement).
● If it is not possible to achieve the exact requirement, return -1.
Examples:
Example 1:
Input:
requirement = 5
● sizes = [3, 5]
● Explanation: A single umbrella of size 5 can exactly shelter 5 people.
● Output:
1
Example 2:
Input:
requirement = 8
● sizes = [3, 5]
● Explanation: It is possible to use:
○ One umbrella of size 5, and
○ One umbrella of size 3, to cover exactly 8 people.
● Output:
2
Example 3:
Input:
requirement = 7
● sizes = [3, 5]
● Explanation: There is no combination of umbrellas that can exactly shelter 7 people.
● Output:
-1
Example 4:
Input:
requirement = 10
● sizes = [3, 5]
● Explanation: It is possible to use two umbrellas of size 5 to cover exactly 10 people.
● Output:
2
Example 5:
Input:
requirement = 4
● sizes = [2, 3]
● Explanation: The only way to meet the exact requirement of 4 is to use two umbrellas of
size 2.
● Output:
2
Example 6:
Input:
requirement = 12
● sizes = [3, 6, 9]
● Explanation: It is possible to use two umbrellas of size 6 to cover exactly 12 people.
● Output:
2
Constraints:
1. Define a DP Array:
○ Let dp[i] represent the minimum number of umbrellas needed to exactly shelter
i people.
○ Initialize the array as dp = [inf] * (requirement + 1) because we aim
to minimize the number of umbrellas.
○ Set dp[0] = 0 since no umbrellas are needed to shelter 0 people.
2. Iterate Over Each Requirement:
○ For every i from 1 to requirement, iterate over all umbrella sizes.
○If an umbrella size size can fit within i (i.e., i >= size), update the DP value
as:
dp[i] = min(dp[i], dp[i - size] + 1)
3. Final Check:
○ If dp[requirement] is still inf after processing, it means there is no
combination of umbrellas that can meet the exact requirement. Return -1.
○ Otherwise, return dp[requirement].
Python Implementation:
from math import inf
# Initialize a DP array to store the minimum number of umbrellas for each requirement
dp = [inf] * (requirement + 1)
dp[0] = 0 # Base case: 0 umbrellas are needed to shelter 0 people
# Examples
print(min_umbrellas(5, [3, 5])) # Output: 1
print(min_umbrellas(8, [3, 5])) # Output: 2
print(min_umbrellas(7, [3, 5])) # Output: -1
print(min_umbrellas(10, [3, 5])) # Output: 2
print(min_umbrellas(4, [2, 3])) # Output: 2
print(min_umbrellas(12, [3, 6, 9])) # Output: 2
Time Complexity:
Space Complexity: