LeetCode 2591. 将钱分给最多的儿童 C#
原题链接
简单
作者:
hpstory
,
2023-03-19 14:18:24
,
所有人可见
,
阅读 29
C# 二分查找代码
public class Solution {
public int DistMoney(int money, int children) {
if (money < children) return -1;
money = money - children;
int left = 0, right = children;
while (left < right){
int mid = left + right + 1 >> 1;
if (Check(mid)) left = mid;
else right = mid - 1;
}
return left;
bool Check(int x){
if (x * 7 > money) return false;
if (x * 7 == money) return true;
int t = money - x * 7;
if (x == children - 1 && t == 3) return false;
if (x == children && t > 0) return false;
return true;
}
}
}
C# 模拟代码
public class Solution {
public int DistMoney(int money, int children) {
if (money < children) return -1;
money -= children;
int result = Math.Min(money / 7, children);
money -= result * 7;
children -= result;
if ((children == 0 && money > 0) || (children == 1 && money == 3)) result--;
return result;
}
}