1927. Sum Game Medium

@problem@discussion
#Math#Greedy#Game Theory



1/**
2 * [1927] Sum Game
3 *
4 * Alice and Bob take turns playing a game, with Alice starting first.
5 * You are given a string num of even length consisting of digits and '?' characters. On each turn, a player will do the following if there is still at least one '?' in num:
6 * <ol>
7 * 	Choose an index i where num[i] == '?'.
8 * 	Replace num[i] with any digit between '0' and '9'.
9 * </ol>
10 * The game ends when there are no more '?' characters in num.
11 * For Bob to win, the sum of the digits in the first half of num must be equal to the sum of the digits in the second half. For Alice to win, the sums must not be equal.
12 * 
13 * 	For example, if the game ended with num = "243801", then Bob wins because 2+4+3 = 8+0+1. If the game ended with num = "243803", then Alice wins because 2+4+3 != 8+0+3.
14 * 
15 * Assuming Alice and Bob play optimally, return true if Alice will win and false if Bob will win.
16 *  
17 * Example 1:
18 * 
19 * Input: num = "5023"
20 * Output: false
21 * Explanation: There are no moves to be made.
22 * The sum of the first half is equal to the sum of the second half: 5 + 0 = 2 + 3.
23 * 
24 * Example 2:
25 * 
26 * Input: num = "25??"
27 * Output: true
28 * Explanation: Alice can replace one of the '?'s with '9' and it will be impossible for Bob to make the sums equal.
29 * 
30 * Example 3:
31 * 
32 * Input: num = "?3295???"
33 * Output: false
34 * Explanation: It can be proven that Bob will always win. One possible outcome is:
35 * - Alice replaces the first '?' with '9'. num = "93295???".
36 * - Bob replaces one of the '?' in the right half with '9'. num = "932959??".
37 * - Alice replaces one of the '?' in the right half with '2'. num = "9329592?".
38 * - Bob replaces the last '?' in the right half with '7'. num = "93295927".
39 * Bob wins because 9 + 3 + 2 + 9 = 5 + 9 + 2 + 7.
40 * 
41 *  
42 * Constraints:
43 * 
44 * 	2 <= num.length <= 10^5
45 * 	num.length is even.
46 * 	num consists of only digits and '?'.
47 * 
48 */
49pub struct Solution {}
50
51// problem: https://leetcode.com/problems/sum-game/
52// discuss: https://leetcode.com/problems/sum-game/discuss/?currentPage=1&orderBy=most_votes&query=
53
54// submission codes start here
55
56impl Solution {
57    pub fn sum_game(num: String) -> bool {
58        false
59    }
60}
61
62// submission codes end
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67
68    #[test]
69    fn test_1927() {
70    }
71}
72


Back
© 2025 bowen.ge All Rights Reserved.