1145. Lead Changes

Easy1.5 points estimatedSimulationCountingPrefix Sum

A basketball scoreboard is replayed from a list of scoring events. For each value in events, a positive number x means team A scored x points and a negative number means team B scored -x points. After every event the team with the higher running total is the leader. When the totals are equal there is no leader at that moment, and the most recent leader stays on record. Return how many times the leader changed, meaning events after which the leader differs from the one on record. The first time any team gets ahead is not a change, so A leading, then a tie, then B leading is one change, while A leading, a tie, then A leading again is none.

1 <= events.length <= 10^4 and 1 <= |events[i]| <= 100. One pass with O(1) extra space is intended.

Example 1

Input:
events = [3,-5,2,4]
Output:
2
Explanation:

Scores run 3-0, 3-5, 5-5, 9-5: A leads, then B, then a tie keeps B on record, then A leads, so the leader changes twice.

Example 2

Input:
events = [2,-2,3]
Output:
0
Explanation:

A leads, the tie keeps A on record, and A leads again, so there are no changes.

Example 3

Input:
events = [-4,4,4,-9]
Output:
2
Explanation:

B leads, a tie, then A leads (one change), then B leads again (a second change).

Constraints

1 ≤ events.length ≤ 104

1 ≤ |events[i]| ≤ 100

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.

Expected complexity

Time
O(n)
Space
O(1)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…