Minimum Operations to Make Array Equal to Target - Problem
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 & Output
Example 1 — Basic Case
$
Input:
nums = [3,5,1,2], target = [4,6,2,4]
›
Output:
7
💡 Note:
We need to transform [3,5,1,2] to [4,6,2,4]. Optimal operations: increment subarray [0,1] by 1, increment subarray [2,3] by 1, then increment subarray [3,3] by 2. Total: 2 + 2 + 2 + 1 = 7 operations.
Example 2 — All Same Target
$
Input:
nums = [1,3,2], target = [2,1,4]
›
Output:
5
💡 Note:
Transform [1,3,2] to [2,1,4]: increment nums[0] by 1, decrement nums[1] by 2, increment nums[2] by 2. Operations: 1 + 2 + 2 = 5.
Example 3 — Already Equal
$
Input:
nums = [1,2,3], target = [1,2,3]
›
Output:
0
💡 Note:
Arrays are already equal, no operations needed.
Constraints
- 1 ≤ nums.length == target.length ≤ 105
- 1 ≤ nums[i], target[i] ≤ 108
Visualization
Tap to expand
Understanding the Visualization
1
Input Arrays
nums = [3,5,1,2] and target = [4,6,2,4]
2
Calculate Differences
Find diff[i] = target[i] - nums[i] for each position
3
Optimal Operations
Use subarray operations to minimize total operations
Key Takeaway
🎯 Key Insight: Separate positive and negative differences to optimize subarray operations
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code