You are given two positive integer arrays nums and target of the same length. Your goal is to transform the nums array to exactly match the target array using the minimum number of operations.
In each operation, you can:
- Select any contiguous subarray of
nums - Either increment all elements in that subarray by 1, or decrement all elements in that subarray by 1
The key insight is that you can choose different subarrays in each operation, and the subarrays can overlap or be completely separate. You want to find the minimum total number of operations needed to make nums[i] == target[i] for all indices.
Example: If nums = [3,5,1,2] and target = [4,6,2,4], you need to increase the first element by 1, second by 1, third by 1, and fourth by 2. The challenge is to do this efficiently by choosing optimal subarrays.
Input & Output
Visualization
Time & Space Complexity
Single pass through the array, each element processed once
Only need a few variables to track the current operation levels
Constraints
- 1 โค nums.length == target.length โค 105
- 1 โค nums[i], target[i] โค 108
- Both arrays have the same length
- All array elements are positive integers