Minimum Number of Increments on Subarrays to Form a Target Array - Problem
You are given an integer array target. You have an integer array initial of the same size as target with all elements initially zeros.
In one operation you can choose any subarray from initial and increment each value by one.
Return the minimum number of operations to form a target array from initial.
The test cases are generated so that the answer fits in a 32-bit integer.
Input & Output
Example 1 — Basic Mountain Shape
$
Input:
target = [1,2,3,2,1]
›
Output:
3
💡 Note:
We need 3 operations: first element (1), increase to 2 (+1), increase to 3 (+1). Decreases are free since we can extend previous operations.
Example 2 — Multiple Peaks
$
Input:
target = [3,1,1,2]
›
Output:
4
💡 Note:
Start with 3 operations for first element. Then 1≤3 (free), 1=1 (free), 2>1 so add 1 more. Total: 3+0+0+1=4.
Example 3 — Increasing Sequence
$
Input:
target = [1,1,2,3]
›
Output:
3
💡 Note:
First element needs 1 operation. Second is same (free). Then +1 for height 2, +1 for height 3. Total: 1+0+1+1=3.
Constraints
- 1 ≤ target.length ≤ 105
- 1 ≤ target[i] ≤ 105
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code