3847. Find the Score Difference in a Game
Description
You are given an integer array nums, where nums[i] represents the points scored in the ith game.
There are exactly two players. Initially, the first player is active and the second player is inactive.
The following rules apply sequentially for each game i:
- If
nums[i]is odd, the active and inactive players swap roles. - In every 6th game (that is, game indices
5, 11, 17, ...), the active and inactive players swap roles. - The active player plays the
ithgame and gainsnums[i]points.
Return the score difference, defined as the first player's total score minus the second player's total score.
Β
Example 1:
Input: nums = [1,2,3]
Output: 0
Explanation:βββββββ
- Game 0: Since the points are odd, the second player becomes active and gains
nums[0] = 1point. - Game 1: No swap occurs. The second player gains
nums[1] = 2points. - Game 2: Since the points are odd, the first player becomes active and gains
nums[2] = 3points. - The score difference is
3 - 3 = 0.
Example 2:
Input: nums = [2,4,2,1,2,1]
Output: 4
Explanation:
- Games 0 to 2: The first player gains
2 + 4 + 2 = 8points. - Game 3: Since the points are odd, the second player is now active and gains
nums[3] = 1point. - Game 4: The second player gains
nums[4] = 2points. - Game 5: Since the points are odd, the players swap roles. Then, because this is the 6th game, the players swap again. The second player gains
nums[5] = 1point. - The score difference is
8 - 4 = 4.
Example 3:
Input: nums = [1]
Output: -1
Explanation:
- Game 0: Since the points are odd, the second player is now active and gains
nums[0] = 1point. - The score difference is
0 - 1 = -1.
Β
Constraints:
1 <= nums.length <= 10001 <= nums[i] <= 1000
Solutions
Solution 1: Simulation
We use a variable \(k\) to represent the role of the current player. Initially \(k = 1\), when \(k = 1\) it means the first player is the active player, and when \(k = -1\) it means the second player is the active player. For each game, we update the value of \(k\) according to the problem description, and add the score of the current game multiplied by \(k\) to the answer. Finally, we return the answer.
The time complexity is \(O(n)\), where \(n\) is the length of the array \(\textit{nums}\). The space complexity is \(O(1)\).
1 2 3 4 5 6 7 8 9 10 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | |