Leetcode 2591. Distribute Money to Maximum Children
You are given an integer money
representing the total amount of money you have, and an integer children
representing the number of children to distribute the money to. You need to distribute all the money according to the following rules:
Your goal is to maximize the number of children who receive exactly 8 dollars.
Return the maximum number of children who can receive exactly 8 dollars.
Before we proceed, let’s clarify a few points to ensure the problem is well-understood:
money
is less than children
. If yes, return 0.money
by 8 and then taking the minimum with children
(min(money / 8, children)
).Here is the C++ implementation of the solution:
#include <algorithm>
using namespace std;
class Solution {
public:
int distMoney(int money, int children) {
// Check if not enough money to give each child 1 dollar
if (money < children) return 0;
// Calculate initial number of children we can give exactly 8 dollars
int maxChildrenWithEightDollars = min(money / 8, children);
// Calculate remaining money after giving 8 dollars to maxChildrenWithEightDollars children
int remainingMoney = money - (8 * maxChildrenWithEightDollars);
int remainingChildren = children - maxChildrenWithEightDollars;
// Adjust the counts if we have more children than remaining money
while (remainingMoney < remainingChildren && maxChildrenWithEightDollars > 0) {
// We need to adjust by reducing the number of children getting exactly 8 dollars
maxChildrenWithEightDollars--;
remainingMoney += 8;
remainingChildren++;
}
// If there is still not enough remaining money for the remaining children, return 0
if (remainingMoney < remainingChildren) return 0;
return maxChildrenWithEightDollars;
}
};
The time complexity of this solution is (O(1)). The operations performed are simple arithmetic operations and conditional checks, which run in constant time.
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?