You are given two positive integer arrays nums and target, of the same length.
In a single operation, you can select any subarray of nums and increment each element within that subarray by 1 or decrement each element within that subarray by 1.
Return the minimum number of operations required to make nums equal to the array target.
Input: nums =[3,5,1,2], target =[4,6,2,4]Output: 2Explanation:
We will perform the following operations to make `nums` equal to `target`:\- Increment `nums[0..3]` by 1,`nums = [4,6,2,3]`.\- Increment `nums[3..3]` by 1,`nums = [4,6,2,4]`.
Input: nums =[1,3,2], target =[2,1,4]Output: 5Explanation:
We will perform the following operations to make `nums` equal to `target`:\- Increment `nums[0..0]` by 1,`nums = [2,3,2]`.\- Decrement `nums[1..1]` by 1,`nums = [2,2,2]`.\- Decrement `nums[1..1]` by 1,`nums = [2,1,2]`.\- Increment `nums[2..2]` by 1,`nums = [2,1,3]`.\- Increment `nums[2..2]` by 1,`nums = [2,1,4]`.
The only thing that matters is the difference between nums[i] and target[i] at each position. Since we can increment or decrement any subarray, the minimum number of operations is the sum of absolute changes between consecutive positions in the difference array.
classSolution {
publicintminOperations(int[] nums, int[] target) {
int n = nums.length, ans = Math.abs(nums[0]- target[0]);
for (int i = 1; i < n; ++i) {
ans += Math.abs((nums[i]- target[i]) - (nums[i-1]- target[i-1]));
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
classSolution {
funminOperations(nums: IntArray, target: IntArray): Int {
var ans = kotlin.math.abs(nums[0] - target[0])
for (i in1 until nums.size) {
ans += kotlin.math.abs((nums[i] - target[i]) - (nums[i-1] - target[i-1]))
}
return ans
}
}
1
2
3
4
5
6
classSolution:
defminOperations(self, nums: list[int], target: list[int]) -> int:
ans: int = abs(nums[0] - target[0])
for i in range(1, len(nums)):
ans += abs((nums[i] - target[i]) - (nums[i-1] - target[i-1]))
return ans
1
2
3
4
5
6
7
8
9
impl Solution {
pubfnmin_operations(nums: Vec<i32>, target: Vec<i32>) -> i32 {
letmut ans = (nums[0] - target[0]).abs();
for i in1..nums.len() {
ans += ((nums[i] - target[i]) - (nums[i-1] - target[i-1])).abs();
}
ans
}
}