Minimum Total Operations - Problem

Given an array of integers nums, you can perform any number of operations on this array. In each operation, you can:

  • Choose a prefix of the array
  • Choose an integer k (which can be negative) and add k to each element in the chosen prefix

A prefix of an array is a subarray that starts from the beginning of the array and extends to any point within it.

Return the minimum number of operations required to make all elements in the array equal.

Input & Output

Example 1 — Basic Case
$ Input: nums = [1,3,2]
Output: 2
💡 Note: Target is 2 (last element). Element at index 1 (value 3) differs from 2, needs 1 operation. Element at index 0 (value 1) differs from 2, needs 1 operation. Total: 2 operations.
Example 2 — Already Equal
$ Input: nums = [2,2,2]
Output: 0
💡 Note: All elements are already equal to 2, so no operations needed.
Example 3 — Single Element
$ Input: nums = [5]
Output: 0
💡 Note: Single element array is already equal, requires 0 operations.

Constraints

  • 1 ≤ nums.length ≤ 105
  • -109 ≤ nums[i] ≤ 109

Visualization

Tap to expand
Minimum Total Operations Greedy Approach - Right to Left INPUT Array nums: 1 idx 0 3 idx 1 2 idx 2 Adjacent Differences: nums[1]-nums[0] +2 nums[2]-nums[1] -1 Goal: Make all elements equal using prefix ops Prefix op: Add k to nums[0...i] for any i ALGORITHM STEPS 1 Scan Right to Left Count sign changes in diffs 2 Calculate Differences diff[i] = nums[i+1]-nums[i] 3 Count Operations Each unique diff = 1 op 4 Return Count Total distinct adjustments Execution Trace: i=2: diff=-1 (need op 1) i=1: diff=+2 (need op 2) Sign changes: 2 ops total ops = 2 FINAL RESULT Output: 2 Solution Steps: Operation 1: Add -1 to prefix[0..2] [1,3,2] --> [0,2,1] Operation 2: Add -1 to prefix[0..1] [0,2,1] --> [-1,1,1] After more adjustments: [x, x, x] - All equal! Key Insight: The minimum operations equals the number of distinct non-zero differences between adjacent elements. Each prefix operation can fix one "level change" in the array. Processing right-to-left, we count how many times the cumulative difference changes sign or magnitude - this gives minimum ops. TutorialsPoint - Minimum Total Operations | Greedy Approach - Right to Left O(n) Time | O(1) Space
Asked in
Google 15 Amazon 12 Microsoft 8
34.7K Views
Medium Frequency
~15 min Avg. Time
890 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