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
Transform Initial [0,0,0,0] to Target [3,1,1,2]Initial Array:0000Target Array:3112TransformOperations needed:• Position 0: Build height 3 → 3 operations• Position 1: Height 1 ≤ 3 → 0 operations (free)• Position 2: Height 1 = 1 → 0 operations (free)• Position 3: Height 2 > 1 → 1 operationTotal: 3 + 0 + 0 + 1 = 4 operations
Understanding the Visualization
1
Input
Target array [3,1,1,2] and initial [0,0,0,0]
2
Process
Count operations needed: first element + increases only
3
Output
Minimum operations: 4
Key Takeaway
🎯 Key Insight: Only count upward jumps - you get downward coverage for free from previous operations
Asked in
Amazon 15 Google 12
89.0K Views
Medium Frequency
~15 min Avg. Time
1.8K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen