Problem · Array
Minimum Operations to Transform Array
Learn this problemProblem statement
You are given two integer arrays:
awith lengthnbwith lengthn + 1
You may perform the following operations on a:
- Increment any element by
1. - Decrement any element by
1. - Copy any current element of
aand append the copy to the end ofa.
After all operations, the first n positions of a must equal the first n positions of b, and the appended element must equal b[n].
Return the minimum number of operations required.
Function
minimumOperationsToTransformArray(a: int[], b: int[]) → longExamples
Example 1
a = [1]b = [2,3]return = 3Increment 1 to 2, copy the value, then increment the copied value to 3. This takes 3 operations.
Example 2
a = [3,3,3]b = [3,3,3,3]return = 1Copy any existing 3 and append it to the end.
Example 3
a = [5,2,1,4,6]b = [4,1,5,4,6,7]return = 8The first five positions require 6 total increment/decrement operations. Copying a value costs 1; the best copied value can be adjusted to 7 with one additional operation, for a total of 8.
Constraints
aandbare integer arrays.ahas lengthn, andbhas lengthn + 1.