leetcode
leetcode 2251 ~ 2300
将钱分给最多的儿童

将钱分给最多的儿童

难度:

标签:

题目描述

You are given an integer money denoting the amount of money (in dollars) that you have and another integer children denoting the number of children that you must distribute the money to.

You have to distribute the money according to the following rules:

  • All money must be distributed.
  • Everyone must receive at least 1 dollar.
  • Nobody receives 4 dollars.

Return the maximum number of children who may receive exactly 8 dollars if you distribute the money according to the aforementioned rules. If there is no way to distribute the money, return -1.

 

Example 1:

Input: money = 20, children = 3
Output: 1
Explanation: 
The maximum number of children with 8 dollars will be 1. One of the ways to distribute the money is:
- 8 dollars to the first child.
- 9 dollars to the second child. 
- 3 dollars to the third child.
It can be proven that no distribution exists such that number of children getting 8 dollars is greater than 1.

Example 2:

Input: money = 16, children = 2
Output: 2
Explanation: Each child can be given 8 dollars.

 

Constraints:

  • 1 <= money <= 200
  • 2 <= children <= 30

代码结果

运行时间: 22 ms, 内存: 16.0 MB


/*
 * 思路:
 * 与上面的解法相同,但是使用Java Stream对代码进行处理和简化。
 */
import java.util.stream.IntStream;

public int maxChildrenWith8DollarsStream(int money, int children) {
    if (money < children) return -1;
    int remaining = money - children;
    int max8 = Math.min(children, remaining / 7);
    return IntStream.rangeClosed(0, max8)
                    .filter(max -> (remaining - max * 7) != 0 || max < children)
                    .max()
                    .orElse(-1);
}

解释

方法:

此题解采用贪心策略,首先确保每个儿童至少得到1美元。然后尝试最大化获得8美元的儿童数量。首先,每个儿童至少分配1美元,然后计算剩余可用金额,尝试尽可能多地安排每个儿童获得8美元(每个儿童多分配7美元)。计算可以这样安排的最大儿童数量,然后从总金额中减去相应的值。如果剩余的钱正好为3美元且只剩一个儿童,或者没有剩余儿童但还有剩余金额,则需要从之前计算的结果中减去一个儿童,因为这表明无法将所有剩余金额分配给任何剩余的儿童而不违反规则。

时间复杂度:

O(1)

空间复杂度:

O(1)

代码细节讲解

🦆
在算法中,如何确保实现了题目要求的‘没有人获得4美元’这一条件?
题解中的算法设计确保每个儿童最少得到1美元,并尝试使他们尽可能得到8美元。通过这种方式,算法避免了分配4美元的情况。算法只考虑1美元和8美元两种情况,确保不出现给任何儿童分配4美元的情况。
🦆
为什么选择每个儿童最初只分配1美元,这样的初始化方式有什么特别的原因吗?
选择每个儿童最初分配1美元是为了确保基本的公平性,每个儿童至少得到一些金额,符合题目要求。这也是为了简化后续的计算,一旦确保每个儿童至少得到1美元,剩余的金额可以用来尝试实现其他的优化条件,如尽量多的儿童获得8美元。
🦆
算法中提到,如果剩余的钱是3美元且只剩一个儿童,或者没有剩余儿童但还有剩余金额时,需要减去一个儿童。这种处理方式是否可能导致非最优的分配结果?
这种处理方式确实可能导致非最优的分配结果。因为减去一个已经计入的儿童意味着减少了能够接近题目要求的儿童数量。这是算法处理剩余情况的一种简化方式,但可能不是最优解,特别是在处理边界条件时。更优的处理可能需要更复杂的逻辑来确保所有剩余金额都能以最优方式分配。
🦆
在尝试最多分配给每个儿童额外7美元时,如果剩余金额不足以给所有儿童各分配7美元,算法是如何处理的?
在这种情况下,算法通过计算`money // 7`来确定最多能给多少儿童分配额外的7美元。这保证了算法不会尝试分配超出剩余金额的资金。计算得到的结果不会超过实际可用的额外金额或儿童数。如果剩余金额不足以给每个儿童分配额外的7美元,则只有部分儿童能得到额外的7美元,其余儿童仍然只能保持最初的1美元。

相关问题