FastPrepFastPrep
Problem Brief

Equalize The Arrays

FULLTIMEOA

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𓂃🖊 🌷

1Example 1

Input
source = [1, 2, 3, -1, 0], target = [3, 4, 3, 0, 4]
Output
6
Explanation

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.

2Example 2

Input
source = [1, 2, 2], target = [2, 2, 3]
Output
2
Explanation
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.

3Example 3

Input
source = [1, 2, 2], target = [2, 2, 3]
Output
2
Explanation
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

Limits and guarantees your solution can rely on.

🐭🐭
public int getMinOperations(int[] source, int[] target) {
  // write your code here
}
Input

source

[1, 2, 3, -1, 0]

target

[3, 4, 3, 0, 4]

Output

6

Sign in to submit your solution.