Minimum Levels to Gain More Points - Problem

You are given a binary array possible of length n. Alice and Bob are playing a game that consists of n levels. Some of the levels in the game are impossible to clear while others can always be cleared.

In particular, if possible[i] == 0, then the i-th level is impossible to clear for both the players. A player gains 1 point on clearing a level and loses 1 point if the player fails to clear it.

At the start of the game, Alice will play some levels in the given order starting from the 0-th level, after which Bob will play for the rest of the levels. Alice wants to know the minimum number of levels she should play to gain more points than Bob, if both players play optimally to maximize their points.

Return the minimum number of levels Alice should play to gain more points. If this is not possible, return -1. Note that each player must play at least 1 level.

Input & Output

Example 1 — Basic Case
$ Input: possible = [1,0,1,0]
Output: 1
💡 Note: Alice plays level 0 (gains 1 point), Bob plays levels 1,2,3 (loses 1, gains 1, loses 1 = -1 total). Alice: 1, Bob: -1, so Alice wins with just 1 level.
Example 2 — Need More Levels
$ Input: possible = [1,1,1,0]
Output: 3
💡 Note: If Alice plays 1 level: Alice=1, Bob=2+(-1)=1 (tie). If Alice plays 2 levels: Alice=2, Bob=1+(-1)=0, Alice wins. Actually Alice needs 3 levels to guarantee more points.
Example 3 — Impossible
$ Input: possible = [0,0]
Output: -1
💡 Note: Both levels are impossible. Both players will lose points, so Alice cannot gain more points than Bob.

Constraints

  • 2 ≤ possible.length ≤ 105
  • possible[i] is either 0 or 1

Visualization

Tap to expand
Minimum Levels to Gain More PointsInput: [1,0,1,0]1010+1 point-1 point+1 point-1 pointAliceBobScore: +1Score: -1+1-1 = -1Alice wins: 1 > -1Answer: 1
Understanding the Visualization
1
Input
Binary array [1,0,1,0] representing clearable levels
2
Split Strategy
Find minimum levels for Alice to beat Bob
3
Output
Return minimum number of levels (1)
Key Takeaway
🎯 Key Insight: Use prefix sums to efficiently compare Alice's cumulative score against Bob's remaining score
Asked in
Google 45 Amazon 38 Microsoft 32
23.4K Views
Medium Frequency
~18 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen