Minimum Number of Increments on Subarrays to Form a Target Array

Hard

Company Tags

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.

A subarray is a contiguous non-empty sequence of elements within an array.

Example 1:

Input: target = [3,1,5,4,2,3,4,2]

Output: 9

Explanation: [0,0,0,0,0,0,0,0] -> [1,1,1,1,1,1,1,1] -> [2,1,1,1,1,1,1,1] -> [3,1,1,1,1,1,1,1] -> [3,1,2,2,2,2,2,2] -> [3,1,2,2,2,3,3,2] -> [3,1,2,2,2,3,4,2] -> [3,1,3,3,2,3,4,2] -> [3,1,4,4,2,3,4,2] -> [3,1,5,4,2,3,4,2].

Example 2:

Input: target = [3,1,1,2]

Output: 4

Explanation: [0,0,0,0] -> [1,1,1,1] -> [1,1,1,2] -> [2,1,1,2] -> [3,1,1,2].

Constraints:

  • 1 <= target.length <= 100,000
  • 1 <= target[i] <= 100,000


Company Tags

Please upgrade to NeetCode Pro to view company tags.

target =