Dare2Solve
You are given two positive integer arrays nums
and target
, both of the same length. In a single operation, you can select any subarray of nums
and increment or decrement each element within that subarray by 1. Your task is to return the minimum number of operations required to make nums
equal to the array target
.
The main challenge is to align the values of nums
with target
using the fewest operations. By focusing on the differences between corresponding elements in nums
and target
, we can devise a strategy to efficiently achieve this alignment.
nums
and target
.incr
and decr
, to track ongoing positive and negative adjustments needed as you iterate through the differences.incr
, increment the operation count by the surplus needed to adjust.decr
, increment the operation count by the surplus needed to adjust.incr
and decr
counters accordingly.nums
equal to target
.class Solution {
public:
long long minimumOperations(vector<int>& nums, vector<int>& target) {
long long inc = 0, dec = 0, res = 0;
for (int i = 0; i < nums.size(); ++i) {
int d = target[i] - nums[i];
if (d > 0) {
if (inc < d) res += d - inc;
inc = d;
dec = 0;
} else if (d < 0) {
if (dec < -d) res += -d - dec;
dec = -d;
inc = 0;
} else {
inc = 0;
dec = 0;
}
}
return res;
}
};
class Solution:
def minimumOperations(self, nums: List[int], target: List[int]) -> int:
inc = 0
dec = 0
res = 0
for i in range(len(nums)):
d = target[i] - nums[i]
if d > 0:
if inc < d:
res += d - inc
inc = d
dec = 0
elif d < 0:
if dec < -d:
res += -d - dec
dec = -d
inc = 0
else:
inc = 0
dec = 0
return res
class Solution {
public long minimumOperations(int[] nums, int[] target) {
long inc = 0, dec = 0, res = 0;
for (int i = 0; i < nums.length; i++) {
int d = target[i] - nums[i];
if (d > 0) {
if (inc < d) res += d - inc;
inc = d;
dec = 0;
} else if (d < 0) {
if (dec < -d) res += -d - dec;
dec = -d;
inc = 0;
} else {
inc = 0;
dec = 0;
}
}
return res;
}
}
var minimumOperations = function (nums, target) {
var inc = 0, dec = 0, res = 0;
for (var i = 0; i < nums.length; i++) {
var d = target[i] - nums[i];
if (d > 0) {
if (inc < d) res += d - inc;
inc = d;
dec = 0;
} else if (d < 0) {
if (dec < -d) res += -d - dec;
dec = -d;
inc = 0;
} else inc = dec = 0;
}
return res;
};