1237. Upbeat Stretches

A music app scores each track in a playlist: a positive number means upbeat, a negative number means gloomy and zero means neutral. Only the sign of a score matters, never its size. Given the array nums, count the non-empty contiguous stretches that contain strictly more positive scores than negative ones. Neutral tracks are ignored, and stretches at different positions are counted separately even if their contents look alike.

Return the count as a long. Think of a running balance that goes up by one for a positive score, down by one for a negative score and stays put for zero: a stretch qualifies when the balance at its end is higher than at its start. Because the balance moves by at most one, you can keep a count per balance value and a running total of earlier balances below the current one.

The intended solution runs in O(n) time and O(n) space.

Example 1

Input:
nums = [2,-1,3]
Output:
3
Explanation:

The qualifying stretches are [2], [2, -1, 3] and [3]; the stretches [2, -1] and [-1, 3] tie one positive against one negative.

Example 2

Input:
nums = [0,0]
Output:
0
Explanation:

Zeros are neutral, so no stretch has strictly more positives than negatives.

Constraints

1 ≤ nums.length ≤ 2 * 105

-109 ≤ nums[i] ≤ 109

The answer fits in a 64-bit integer.

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 4,000 msC++ 1,000 msJava 2,000 msJavaScript 2,000 msTypeScript 2,000 ms

Expected complexity

Time
O(n)
Space
O(n)

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…