← Back to companies
[ OK ] Loaded —
[ INFO ]
$ cd
$ ls -lt
01
02
03
04
05
$ ls -lt
01
02
03
04
05
user@intervues:~/$
You are given two integer arrays source and target of equal length n. In a single operation you may perform either of the following on source:
source[0..i] and add 1 to every element in it.source[i..n-1] and add 1 to every element in it.Return the minimum number of operations required to transform source into target. If it is impossible, return -1.
Examples:
source = [1, 1, 1, 1, 1] target = [3, 4, 5, 4, 3] result = 4 -> +1 on prefix[0..4] -> [2,2,2,2,2] -> +1 on prefix[0..2] -> [3,3,3,2,2] -> +1 on prefix[0..1]+suffix[3..4] requires 2 ops, etc.
Key observation: the cost is the sum of positive differences in the derivative d[i] = target[i] - source[i] - (target[i-1] - source[i-1]). If any target[i] < source[i], the answer is -1 because the operations can only add.
Follow-up Questions: