Dynamic programming · Medium
A report must highlight the exact period with the greatest net gain in a signed metric stream. Several periods can have the same gain, so a stable earliest-range rule is required for reproducible highlighting.
Return inclusive start and end indexes of a maximum-sum non-empty contiguous segment using the declared tie rule.
Input
Call
- Implement solve(input) and return the result. The provided adapter handles JSON input and output.
Input shape
{ nums: integer[] }
Fields
- nums is an array of signed integers. Repeated values at different positions are separate entries.
Output
Return value
- Return [start,end] with zero-based inclusive indexes. Empty input returns null.
- First maximize sum. Then choose the smallest start index, then the smallest end index. All-negative input still selects a non-empty segment.
Constraints
- 0 <= nums.length <= 100000; -1000000000 <= nums[i] <= 1000000000.
- All totals and counts fit exactly in a safe JSON integer.
Examples
Example 1
{
"nums": [
0,
2,
-2,
2
]
}Returns
[
0,
1
]Example 2
{
"nums": [
-3,
-1,
-1
]
}Returns
[
1,
1
]Required complexity
O(n) time and O(1) auxiliary space