1238. Long Enough Target Stretches
A shop records its daily profit or loss in the integer array nums. The owner is looking for reporting periods, meaning non-empty contiguous stretches of days, whose profits add up to exactly k, but a period only counts when it lasts at least minLen days. Periods at different positions are different periods even when their contents look alike.
Return how many such periods exist, as a long. Prefix sums can pass the 32-bit range, so use 64-bit arithmetic. A period from day i to day j-1 has sum P[j] - P[i], so when you reach prefix j you may only look back at prefixes that are at least minLen positions earlier: insert each prefix into a hash map of counts when it becomes eligible, then look up P[j] - k.
The intended solution runs in O(n) time and O(n) space.
Example 1
- Input:
- nums = [1,2,3,0,3], k = 3, minLen = 2
- Output:
- 3
- Explanation:
With at least two days, the periods summing to 3 are [1, 2], [3, 0] and [0, 3]; the single-day [3] periods are too short.
Example 2
- Input:
- nums = [-2,5,-3,1], k = 0, minLen = 3
- Output:
- 1
- Explanation:
Only [-2, 5, -3] has sum 0 with three or more days.
Constraints
1 ≤ minLen ≤ nums.length ≤ 2 * 105
-104 ≤ nums[i] ≤ 104
-109 ≤ k ≤ 109
Prefix sums need 64-bit integers.
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)