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
Minimum Operations to Make Array Equal to Target INPUT nums array: 3 5 1 2 target array: 4 6 2 4 diff = target - nums: 1 1 1 2 Goal: Make diff all zeros using min operations ALGORITHM STEPS 1 Compute Differences diff[i] = target[i] - nums[i] 2 Track Sign Changes Count pos/neg transitions 3 Greedy Counting Add |diff| for each segment 4 Sum Operations Total = sum of all changes diff: [1, 1, 1, 2] All positive, continuous Operations needed: |1| + |1-1| + |1-1| + |2-1| + handle increases = 7 FINAL RESULT After 7 operations: nums becomes target: 4 6 2 4 OUTPUT 7 OK - Verified! Minimum operations to transform nums to target using subarray inc/dec Key Insight: The greedy approach uses the difference array to track how much each element needs to change. When consecutive differences have the same sign, we can batch operations. Operations are counted based on the absolute difference changes: sum of |diff[i] - diff[i-1]| for sign changes + initial |diff[0]|. TutorialsPoint - Minimum Operations to Make Array Equal to Target | Greedy with Difference Array
Asked in
Google 45 Meta 38 Amazon 32 Microsoft 28
28.5K Views
Medium Frequency
~35 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen