Problem · Array

Minimum Operations to Make Arrays Equal

Learn this problem
HardMathWorks logoMathWorksFULLTIMEOA

Problem statement

You are given two integer arrays source and target of equal length. In one operation, choose a nonempty prefix or a nonempty suffix of source and add 1 to every selected element.

Return the minimum number of operations needed to make source equal to target. If this is impossible, return -1.

Function

minOperations(source: long[], target: long[]) → long

Examples

Example 1

source = [1, 2, 2]target = [2, 2, 3]return = 2

First, increment the prefix containing only index 0 to change source to [2, 2, 2]. Then increment the suffix beginning at index 2 to obtain [2, 2, 3]. Therefore the minimum is 2.

Constraints

  • source.length = target.length
  • source.length <= 10^5
  • -10^13 <= source[i], target[i] <= 10^13

More MathWorks problems

drafts saved locally
public long minOperations(long[] source, long[] target) {
  // write your code here
}
source[1, 2, 2]
target[2, 2, 3]
expected2
checking account