easyRecursionPattern: Recursion
Resource Allocation Solution
Problem Statement
Given a list of resources and module counts, distribute the resources recursively to each module.
Examples
Example 1:
Input:Resources: [100, 200, 300], Module count: 3
Output:["Resources:NaN","[100,NaN","200,NaN","300],NaN","ModuleNaN","count:NaN",null]
Explanation: The correct output can be derived from the formula: total resource divided by module count, and for remaining resource, recursively do it until the remaining resource becomes zero.
Constraints
- Resources and module count are positive integers.
- Resources are distributed recursively, so the allocation depends on the number of modules.
- The resources are distributed evenly among the modules, but with some remainder, if there is any.
Time: O(n*m) Space: O(1)
Use a recursive formula to distribute the resources among the modules, taking into account the number of modules.
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(resources, module_count):
sum_resources = sum(resources)
allocation = sum_resources / module_count
return [resource + (allocation - resource) * (random.random() - 0.5) for resource in resources]