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: 2
💡 Note: If Alice plays 1 level: Alice=1, Bob=1+1+(-1)=1 (tie). If Alice plays 2 levels: Alice=1+1=2, Bob=1+(-1)=0, Alice wins with 2 levels.
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 Points INPUT possible array (binary) 1 idx 0 0 idx 1 1 idx 2 0 idx 3 1 = clearable (+1 pt) 0 = impossible (-1 pt) A Alice plays first B Bob plays rest GOAL: Find min levels for Alice to score MORE than Bob ALGORITHM STEPS 1 Calculate Total Score Sum: 1-1+1-1 = 0 2 Prefix Sum Approach Alice score = prefix[i] Bob score = total - prefix[i] 3 Check Each Split Need: Alice > Bob i.e. prefix > total/2 i Alice Bob A > B? 1 +1 -1 OK 2 0 0 NO 3 +1 -1 -- 4 Return First Valid First i where Alice wins FINAL RESULT Optimal Split at i=1 1 Alice 0, 1, 0 Bob A plays level 0: +1 pt B plays levels 1,2,3: -1+1-1 = -1 pt Score Comparison: Alice: 1 > Bob: -1 OUTPUT: 1 Key Insight: Use prefix sums to efficiently calculate Alice's and Bob's scores for each possible split point. Alice's score = prefix[i], Bob's score = total - prefix[i]. Find minimum i where Alice's score > Bob's score. Time Complexity: O(n) | Space Complexity: O(1) with running prefix sum. TutorialsPoint - Minimum Levels to Gain More Points | Optimal Solution
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