easyRecursionPattern: Recursion
ResourceAllocationCombinations Solution
Problem Statement
Given integers oxygen, food, and water, find the total number of possible allocations of these resources among a specified number of habitats using recursion.
Examples
Example 1:
Input:{ oxygen: 10, food: 5, water: 7, habitats: 3 }
Output:0
Explanation: 120 possible allocations.
Example 2:
Input:{ oxygen: 100, food: 50, water: 70, habitats: 5 }
Output:0
Explanation: 756,000 possible allocations.
Example 3:
Input:{ oxygen: 0, food: 0, water: 0, habitats: 0 }
Output:0
Explanation: 1 possible allocation.
Constraints
- oxygen, food, and water are non-negative integers.
- habitats is a positive integer.
- The number of habitats is less than or equal to the sum of oxygen, food, and water.
Time: O((3^n)!/((n!)^3)) Space: O(n)
Use recursion to find the total number of possible allocations by considering all possible allocations of resources and their permutations.
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
def resource_allocation_combinations(oxygen, food, water, habitats):
from math import comb
# Calculate the total number of resources
total = oxygen + food + water
# If the number of habitats is greater than the total number of resources,
# the number of combinations is 0
if habitats > total:
return 0
# Use the combination formula to calculate the number of allocations
import math
ans = math.comb(total+habs-1, habs-1)
return ans
