将钱分给最多的儿童
难度:
标签:
题目描述
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美元,这样的初始化方式有什么特别的原因吗?
▷🦆
算法中提到,如果剩余的钱是3美元且只剩一个儿童,或者没有剩余儿童但还有剩余金额时,需要减去一个儿童。这种处理方式是否可能导致非最优的分配结果?
▷🦆
在尝试最多分配给每个儿童额外7美元时,如果剩余金额不足以给所有儿童各分配7美元,算法是如何处理的?
▷