Equalize Arrays with Prefix and Suffix Increments
Learn this problemProblem statement
You are given two integer arrays, source and target, of equal length n.
In one operation, choose an index i and perform exactly one of these actions:
- Add
1to every element in the prefixsource[0..i]. - Add
1to every element in the suffixsource[i..n - 1].
Return the minimum number of operations required to make source equal to target. If the transformation is impossible, return -1.
The source's numeric bounds require 64-bit values, so this practice contract uses long arrays and returns a long.
Complete getMinOperations for the given source and target arrays.
Function
getMinOperations(source: long[], target: long[]) → longExamples
Example 1
source = [1, 2, 2]target = [2, 2, 3]return = 2Increment the prefix ending at index 0, producing [2, 2, 2]. Then increment the suffix starting at index 2, producing [2, 2, 3].
Example 2
source = [1, 1, 1]target = [3, 3, 3]return = 2Increment the whole array twice. A whole-array increment may be represented as either a prefix ending at index n - 1 or a suffix starting at index 0.
Example 3
source = [0, 0, 0, 0, 0]target = [1, 0, 1, 0, 1]return = -1The required increment profile has two separate downward drops, but only one unit is required at the first position. No combination of prefix and suffix increments can create that profile.
Constraints
1 <= n <= 100000source.length = target.length = n-10^13 <= source[i], target[i] <= 10^13- The correct minimum, when it exists, fits in a signed 64-bit integer.