#3847

Find the Score Difference in a Game

Medium
ArraySimulationSimulationArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Use a single pass to track scores while managing player roles based on game rules. This approach is efficient and straightforward.

⚙️

Algorithm

3 steps
  1. 1Step 1: Initialize scores for both players and set the active player.
  2. 2Step 2: Loop through the games, updating scores and swapping roles based on conditions.
  3. 3Step 3: Return the score difference after processing all games.
solution.py11 lines
1def score_difference(nums):
2    p1_score, p2_score = 0, 0
3    active = 1
4    for i in range(len(nums)):
5        if active == 1:
6            p1_score += nums[i]
7        else:
8            p2_score += nums[i]
9        if nums[i] % 2 == 1 or (i + 1) % 6 == 0:
10            active = 2 if active == 1 else 1
11    return p1_score - p2_score

Complexity note: The complexity is linear since we traverse the array once, updating scores in constant time.

  • 1Track player roles efficiently
  • 2Use modular arithmetic for swaps

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.