LeetCode每日一题(2226. Maximum Candies Allocated to K Children)

给定一个表示糖果堆大小的整数数组 candies 和一个整数 k,你需要将糖果分配给 k 个孩子,使得每个孩子获得相同数量的糖果。每个糖果堆可以分成任意多个子堆,但不能合并两个堆。目标是最大化每个孩子能获得的糖果数量。二分查找法可以用于解决这个问题,开始时最小值为 0,最大值为最大糖果堆的数量,通过不断调整边界找到可行的最大糖果数。
摘要由CSDN通过智能技术生成

You are given a 0-indexed integer array candies. Each element in the array denotes a pile of candies of size candies[i]. You can divide each pile into any number of sub piles, but you cannot merge two piles together.

You are also given an integer k. You should allocate piles of candies to k children such that each child gets the same number of candies. Each child can take at most one pile of candies and some piles of candies may go unused.

Return the maximum number of candies each child can get.

Example 1:

Input: candies = [5,8,6], k = 3
Output: 5

Explanation: We can divide candies[1] into 2 piles of size 5 and 3, and candies[2] into 2 piles of size 5 and 1. We now have five piles of candies of sizes 5, 5, 3, 5, and 1. We can allocate the 3 piles of size 5 to 3 children. It can be proven that each child cannot receive more than 5 candies.

Example 2:

Input: candies = [2,5], k = 11
Output: 0

Explanation: There are 11 children but only 7 candies in total, so it is impossible to ensure each child receives at least one candy. Thus, each child gets no candy and the answer is 0.

Constraints:

  • 1 <= candies.length <= 105
  • 1 <= candies[i] <= 107
  • 1 <= k <= 1012

二分法查找, 开始 min 是 0, max 是最大 pile 的数量, mid = (min + max) / 2, 然后检查按 mid 来分够不够分, 不够分的话降低 max, 够分的话增加 min


impl 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值