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
Minimum Increments on Subarrays INPUT Target Array Visualization 1 2 3 2 1 0 1 2 3 target = [1, 2, 3, 2, 1] 1 2 3 2 1 i=0 i=1 i=2 i=3 i=4 ALGORITHM STEPS 1 Initialize ops = target[0] = 1 2 Compare Adjacent For each i: check diff 3 Add Increases Only If t[i] > t[i-1]: add diff 4 Sum All Increases Return total ops Difference Tracking: i=0: ops = 1 (first) i=1: 2-1 = +1 --> ops=2 i=2: 3-2 = +1 --> ops=3 i=3: 2-3 = -1 (skip) i=4: 1-2 = -1 (skip) FINAL RESULT Operations Breakdown Op 1: Subarray [0..4] [0,0,0,0,0] --> [1,1,1,1,1] Op 2: Subarray [1..3] [1,1,1,1,1] --> [1,2,2,2,1] Op 3: Subarray [2..2] [1,2,2,2,1] --> [1,2,3,2,1] OUTPUT 3 OK - 3 operations needed to form target array Key Insight: Count only the POSITIVE differences between adjacent elements. Each increase requires a new operation that extends to all following elements. Decreases are "free" as they're covered by previous operations. Formula: ops = target[0] + sum(max(0, target[i] - target[i-1])) for i > 0 TutorialsPoint - Minimum Number of Increments on Subarrays to Form a Target Array | Greedy Difference Counting
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