Leetcode 2591. Distribute Money to Maximum Children
You are given an integer money
representing the total amount of money you have and another integer children
representing the number of children. Your task is to distribute the money among the children such that each child gets at least one unit of money and no child gets more than 8 units of money. Return the maximum number of children that can receive the money according to the given constraints. If it is not possible to distribute the money, return -1.
children
from money
for initial distribution.public class Solution {
public int distMoney(int money, int children) {
if (money < children) return -1; // Not enough money to give each child 1 unit
// Initial distribution: each child gets one unit
money -= children;
int[] distribution = new int[children];
// Fill distribution with remaining money
for (int i = 0; i < children && money > 0; i++) {
int give = Math.min(7, money);
distribution[i] += give;
money -= give;
}
// Check if excess money remains un-distributed
if (money > 0) return -1;
// Calculate number of children receiving money correctly
int maxChildren = 0;
for (int i = 0; i < children; i++) {
if (distribution[i] > 0) maxChildren++;
}
return maxChildren;
}
}
if (money < children)
takes constant time ( O(1) ).children
iterations, thus taking ( O(children) ) time.Therefore, the overall time complexity is ( O(children) ).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?