98. Binary Stretch Goal
A fitness tracker records one bit per minute in the array nums: 1 means the wearer took a step during that minute and 0 means they stood still. Coaches want to know how often a block of consecutive minutes contains a specific number of active minutes.
Given the integer goal, count the contiguous, non-empty blocks (subarrays) of nums whose values add up to exactly goal. Blocks starting or ending at different positions are counted separately even when their contents look the same. Return the total number of such blocks.
Example 1
- Input:
- nums = [1,0,0,1,1], goal = 2
- Output:
- 4
- Explanation:
The blocks [1,0,0,1], [0,0,1,1], [0,1,1] and [1,1] each sum to 2, so the answer is 4.
Example 2
- Input:
- nums = [0,0,0], goal = 4
- Output:
- 0
- Explanation:
The total of all values is 0, so no block can reach 4 and the answer is 0.
Constraints
- 1 ≤ nums.length ≤ 50000
- nums[i] is either 0 or 1
- 0 ≤ goal ≤ 109
The answer always fits in a 32-bit signed 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 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n)
- Space
- O(n)