Problem · Array

Equalize The Arrays

MediumAmazonFULLTIMEOA
See Amazon hiring insights

Make a source array equal to a target array using some given operations.

More formally, given an array source of length n, either add 1 to any prefix of the array or add 1 to any suffix of the array. That is, in one operation choose some index i and add 1 to source[0], source[1] ... source[i] or add 1 to source[i], source[i + 1]...source[n - 1].

Find the minimum number of operations required to make the arrays equal. If it is impossible to make the two arrays equal, report -1 as the answer.

Function Description

Complete the function getMinOperations in the editor below.

getMinOperations has the following parameters:

  1. int[] source: an array of integers
  2. int[] target: an array of integers

🌷 spike = 100% Awesome𓂃🖊 🌷

Examples
01 · Example 1
source = [1, 2, 3, -1, 0]
target = [3, 4, 3, 0, 4]
return = 6

Given n = 5, source = [1,2,3,-1,0], target = [3,4,3,0,4]

  1. Choose i = 1 and add 1 to the prefix and perform this operation two times - source = [3,4,3,-1,0], target = [3,4,3,0,4]
  2. Choose i = 3 and add 1 to the suffix - source = [3,4,3,0,1], target = [3,4,3,0,4]
  3. Choose i = 4 and add 1 to the suffix and perform this operation three times - source = [3,4,3,0,4], target = [3,4,3,0,4]

The answer is 2 + 1 + 3 = 6.

02 · Example 2
source = [1, 2, 2]
target = [2, 2, 3]
return = 2
We can make the two arrays equal in 2 operations - 1. Choose i = 0 and add 1 to the prefix source = [1, 2, 2] -> [2, 2, 2] 2. Choose i = 2 and add 1 to the suffix source = [2, 2, 2] -> [2, 2, 3] = target Hence, the answer is 2 and it can be shown that it cannot be less than 2.
03 · Example 3
source = [1, 2, 2]
target = [2, 2, 3]
return = 2
We can make the two arrays equal in 2 operations - 1. Choose i = 0 and add 1 to the prefix source = [1, 2, 2] -> [2, 2, 2] 2. Choose i = 2 and add 1 to the suffix source = [2, 2, 2] -> [2, 2, 3] = target Hence, the answer is 2 and it can be shown that it cannot be less than 2.
Constraints
🐭🐭
More Amazon problems
drafts saved locally
public int getMinOperations(int[] source, int[] target) {
  // write your code here
}
source[1, 2, 3, -1, 0]
target[3, 4, 3, 0, 4]
expected6
sign in to submit