Welcome to Subscribe On Youtube
3232. Find if Digit Game Can Be Won
Description
You are given an array of positive integers nums
.
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
.
Example 1:
Input: nums = [1,2,3,4,10]
Output: false
Explanation:
Alice cannot win by choosing either single-digit or double-digit numbers.
Example 2:
Input: nums = [1,2,3,4,5,14]
Output: true
Explanation:
Alice can win by choosing single-digit numbers which have a sum equal to 15.
Example 3:
Input: nums = [5,5,5,25]
Output: true
Explanation:
Alice can win by choosing double-digit numbers which have a sum equal to 25.
Constraints:
1 <= nums.length <= 100
1 <= nums[i] <= 99
Solutions
Solution 1: Summation
According to the problem description, as long as the sum of the units digits is not equal to the sum of the tens digits, Xiaohong can always choose a larger sum to win.
The time complexity is $O(n)$, where $n$ is the length of the array $\textit{nums}$. The space complexity is $O(1)$.
-
class Solution { public boolean canAliceWin(int[] nums) { int a = 0, b = 0; for (int x : nums) { if (x < 10) { a += x; } else { b += x; } } return a != b; } }
-
class Solution { public: bool canAliceWin(vector<int>& nums) { int a = 0, b = 0; for (int x : nums) { if (x < 10) { a += x; } else { b += x; } } return a != b; } };
-
class Solution: def canAliceWin(self, nums: List[int]) -> bool: a = sum(x for x in nums if x < 10) b = sum(x for x in nums if x > 9) return a != b
-
func canAliceWin(nums []int) bool { a, b := 0, 0 for _, x := range nums { if x < 10 { a += x } else { b += x } } return a != b }
-
function canAliceWin(nums: number[]): boolean { let [a, b] = [0, 0]; for (const x of nums) { if (x < 10) { a += x; } else { b += x; } } return a !== b; }