Alice and Bob are playing a game. In the game, Alice can choose either all single-digit numbers or all double-digit numbers from nums, and the rest of the numbers are given to Bob. Alice wins if the sum of her numbers is
strictly greater than the sum of Bob’s numbers.
Return true if Alice can win this game, otherwise, return false.
The key idea is to split the numbers into single-digit and double-digit groups, then check if the sum of either group is strictly greater than the sum of the rest. Alice can only pick all single-digit or all double-digit numbers, so we just need to compare both options.
classSolution {
publicbooleandigitGameCanBeWon(int[] nums) {
int s1 = 0, s2 = 0, total = 0;
for (int n : nums) {
total += n;
if (n < 10) s1 += n;
else s2 += n;
}
return s1 > total - s1 || s2 > total - s2;
}
}
1
2
3
4
5
6
7
8
9
10
classSolution {
fundigitGameCanBeWon(nums: IntArray): Boolean {
var s1 = 0; var s2 = 0; var total = 0for (n in nums) {
total += n
if (n < 10) s1 += n else s2 += n
}
return s1 > total - s1 || s2 > total - s2
}
}
1
2
3
4
5
6
7
8
9
10
classSolution:
defdigitGameCanBeWon(self, nums: list[int]) -> bool:
s1 = s2 = total =0for n in nums:
total += n
if n <10:
s1 += n
else:
s2 += n
return s1 > total - s1 or s2 > total - s2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
impl Solution {
pubfndigit_game_can_be_won(nums: Vec<i32>) -> bool {
let (mut s1, mut s2, mut total) = (0, 0, 0);
for n in nums.iter() {
total += n;
if*n <10 {
s1 += n;
} else {
s2 += n;
}
}
s1 > total - s1 || s2 > total - s2
}
}
1
2
3
4
5
6
7
8
9
10
11
classSolution {
digitGameCanBeWon(nums: number[]):boolean {
lets1=0, s2=0, total=0;
for (constnofnums) {
total+=n;
if (n<10) s1+=n;
elses2+=n;
}
returns1>total-s1||s2>total-s2;
}
}