Problem · Array

Minimum Operations to Make Arrays Equal

HardMathWorksFULLTIMEOA

Given two arrays source and target, return the minimum number of operations to make the arrays equal. If it is impossible return -1. In 1 operation, you can select a prefix or suffix of the array and add 1 to all the elements in the selected subarray.

For example, source = [1,2,2] and target = [2,2,3]. First operation: [2,2,2]. Next operation: [2,2,3]. Answer is 2.

Function Description

Complete the function minOperations in the editor.

minOperations has the following parameters:

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

Returns

int: the minimum number of operations to make the arrays equal or -1 if impossible

Examples
01 · Example 1
source = [1,2,2]
target = [2,2,3]
return = 2

First operation: select the prefix [1] and add 1 to all its elements to get [2,2,2].

Next operation: select the suffix [3] and add 1 to all its elements to get [2,2,3].

The answer is 2 operations.

Constraints
  • Size of the array can be up to 105
  • element are in the range [-1013, 1013]
  • More MathWorks problems
    drafts saved locally
    public int minOperations(int[] source, int[] target) {
      // write your code here
    }
    
    source[1,2,2]
    target[2,2,3]
    expected2
    sign in to submit