Dynamic programming · Medium
A service records signed changes in a running metric. An analyst wants the most beneficial continuous period, with no skipped observations inside that period. Even if all changes are negative, the chosen period must contain an observation.
Return the greatest sum of any non-empty contiguous segment of the supplied changes.
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 in its original order. Equal values at different indexes are separate entries.
Output
Return value
- Return only the maximum sum, not indexes. Empty input returns null.
- For all-negative input select the least-negative non-empty segment; do not return zero.
Constraints
- 0 <= nums.length <= 100000; -1000000000 <= nums[i] <= 1000000000.
- All requested totals and counts fit exactly in a safe JSON integer.
Examples
Example 1
{
"nums": [
4,
-8,
5,
2,
-1
]
}Returns
7Example 2
{
"nums": [
-5,
-2,
-7
]
}Returns
-2Required complexity
O(n) time and O(1) auxiliary space