Skip to content

Commit e355181

Browse files
authored
Create distribute-money-to-maximum-children.cpp
1 parent 637e4f0 commit e355181

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
// Time: O(1)
2+
// Space: O(1)
3+
4+
// greedy
5+
class Solution {
6+
public:
7+
int distMoney(int money, int children) {
8+
if (money < children * 1) {
9+
return -1;
10+
}
11+
money -= children * 1;
12+
const int q = money / 7, r = money % 7;
13+
return min(q, children) - static_cast<int>(q > children || (q == children && r != 0) || (q == children - 1 && r == 3));
14+
}
15+
};
16+
17+
// Time: O(1)
18+
// Space: O(1)
19+
// greedy
20+
class Solution2 {
21+
public:
22+
int distMoney(int money, int children) {
23+
if (money < children * 1) {
24+
return -1;
25+
}
26+
money -= children * 1;
27+
const int q = money / 7, r = money % 7;
28+
if (q > children) {
29+
return children - 1;
30+
}
31+
if (q == children) {
32+
return q - static_cast<int>(r != 0);
33+
}
34+
if (q == children - 1) {
35+
return q - static_cast<int>(r == 3);
36+
}
37+
return q;
38+
}
39+
};

0 commit comments

Comments
 (0)