Dynamic programming · Medium
A maintenance planner can select slots from an ordered schedule, but adjacent slots cannot both be used because a recovery interval is required. Each slot has a signed benefit. Skipping every slot is allowed.
Return the greatest total benefit of a subset that never selects adjacent schedule positions.
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 the benefit total, not the chosen indexes. Empty input and all-negative input return 0.
- The schedule is linear: its first and last slots are not adjacent unless the array has length two.
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": [
5,
6,
5
]
}Returns
10Example 2
{
"nums": [
-2,
-1
]
}Returns
0Required complexity
O(n) time and O(1) auxiliary space