Prefix sum · Hard
A ledger records positive charges and negative refunds in time order. A report needs the longest uninterrupted period whose net charge stays within a chosen budget. Refunds mean that adding another entry can reduce the total, so a positive-only sliding window would be invalid.
Return the greatest length of a non-empty contiguous segment whose signed sum is at most target or zero when no segment qualifies.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[], target: integer }
Fields
- nums contains signed integer adjustments in their original order; target is a signed threshold.
- A segment is a non-empty consecutive range of indexes. Negative values cannot be discarded or replaced by absolute values.
Output
Return value
- Return an integer length, not a sum or pair of indexes. A sum exactly equal to target qualifies.
- Empty input or no qualifying non-empty segment returns zero. The best segment may contain positive values canceled by later negative values.
Constraints
- 0 <= nums.length <= 100000; -1000000000 <= nums[i] <= 1000000000; -100000000000000 <= target <= 100000000000000.
- All prefix sums and results fit a safe JSON integer. Do not mutate input.
Examples
Example 1
{
"nums": [
5,
-4,
3
],
"target": 4
}Returns
3Example 2
{
"nums": [
2,
3
],
"target": 1
}Returns
0Required complexity
O(n log(n + 1)) time and O(n) auxiliary space