algoadvance

Leetcode 2591. Distribute Money to Maximum Children

Problem Statement

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.

Clarifying Questions

  1. Is all the money distributed when it is impossible to distribute the money?
    • The problem is not directly asking this, but our goal is to distribute all of the money if possible while adhering to the constraints.
  2. Can the money or number of children be zero?
    • The problem doesn’t explicitly mention this. We return -1 because distributing zero money to a positive number of children is impossible.
  3. What happens if there are not enough units of money to give at least 1 unit to every child?
    • In such a case, it’s impossible to distribute the money fulfilling the constraints, hence the answer should be -1.

Strategy

  1. Initial Feasibility Check:
    • Check if the money is less than the number of children. If true, return -1 since we need at least 1 unit per child.
  2. Distribute Minimum Units:
    • Each child should get at least 1 unit of money. Subtract children from money for initial distribution.
  3. Remaining Money Distribution:
    • Try to allocate the remaining money optimally by giving each child up to 7 more units (since they already have 1 and cannot exceed 8).
  4. Final Distribution Check:
    • If after allocation we still have money left and all children have exactly 8 units, then we cannot distribute money according to constraints.

Code

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;
    }
}

Time Complexity

Therefore, the overall time complexity is ( O(children) ).

Cut your prep time in half and DOMINATE your interview with AlgoAdvance AI