跳到主要内容

2591.将钱分给最多的儿童

链接:2591.将钱分给最多的儿童
难度:Easy
标签:贪心、数学
简介:请你按照上述规则分配金钱,并返回 最多 有多少个儿童获得 恰好 8 美元。如果没有任何分配方案,返回 -1 。

题解 1 - cpp

  • 编辑时间:2023-09-22
  • 执行用时:4ms
  • 内存消耗:6.05MB
  • 编程语言:cpp
  • 解法介绍:贪心计算。
class Solution {
public:
int distMoney(int money, int children) {
if (money < children) return -1;
int cnt = money / 8, surplus_money = money % 8, surplus_children = children - cnt;
if (cnt == children) return surplus_money == 0 ? children : children - 1;
if (cnt > children) return children - 1;
if (surplus_money == surplus_children) return cnt;
if (surplus_money > surplus_children) return surplus_children == 1 and surplus_money == 4 ? cnt - 1 : cnt;
return cnt - ceil(1.0 * (surplus_children - surplus_money) / 7.0);
}
};

题解 2 - python

  • 编辑时间:2023-09-22
  • 执行用时:52ms
  • 内存消耗:15.61MB
  • 编程语言:python
  • 解法介绍:同上。
class Solution:
def distMoney(self, money: int, children: int) -> int:
if money < children:
return -1
cnt = money // 8
surplus_money = money % 8
surplus_children = children - cnt
if cnt == children:
if surplus_money == 0:
return children
return children - 1
if cnt > children:
return children - 1
if surplus_money == surplus_children:
return cnt
if surplus_money > surplus_children:
if surplus_children == 1 and surplus_money == 4:
return cnt - 1
return cnt
return cnt - ceil((surplus_children - surplus_money) / 7)

题解 3 - rust

  • 编辑时间:2023-09-22
  • 内存消耗:2.58MB
  • 编程语言:rust
  • 解法介绍:同上。
impl Solution {
pub fn dist_money(money: i32, children: i32) -> i32 {
if money < children {
-1
} else {
let (cnt, surplus_money) = (money / 8, money % 8);
let surplus_children = children - cnt;
if cnt == children {
if surplus_money == 0 {
children
} else {
children - 1
}
} else if cnt > children {
children - 1
} else if surplus_money == surplus_children {
cnt
} else if surplus_money > surplus_children {
if surplus_children == 1 && surplus_money == 4 {
cnt - 1
} else {
cnt
}
} else {
cnt - ((surplus_children - surplus_money) as f64 / 7.0).ceil() as i32
}
}
}
}