#3232
Find if Digit Game Can Be Won
EasyArrayMathArrayMath
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n) | O(n) |
| Space | O(1) | O(1) |
💡
Intuition
Time O(n)Space O(1)
The optimal solution is similar to the brute force approach but focuses on calculating the sums in a single pass and directly comparing them. This avoids unnecessary calculations and is efficient.
⚙️
Algorithm
5 steps- 1Step 1: Initialize sum_single and sum_double to 0.
- 2Step 2: Traverse the nums array once to calculate both sums.
- 3Step 3: Calculate total_sum as the sum of all elements in nums.
- 4Step 4: Calculate Bob's sum as total_sum - max(sum_single, sum_double).
- 5Step 5: Return true if sum_single > Bob's sum or sum_double > Bob's sum, otherwise return false.
solution.py11 lines
1def canAliceWin(nums):
2 sum_single = 0
3 sum_double = 0
4 for num in nums:
5 if num < 10:
6 sum_single += num
7 else:
8 sum_double += num
9 total_sum = sum_single + sum_double
10 bob_sum = total_sum - max(sum_single, sum_double)
11 return sum_single > bob_sum or sum_double > bob_sumℹ
Complexity note: The time complexity is O(n) because we only traverse the array once. The space complexity is O(1) since we only use a few extra variables for sums.
- 1Alice's winning condition is based on the sums of single and double-digit numbers.
- 2If Alice's sum of chosen numbers is greater than Bob's remaining numbers, she wins.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.