Reduction Operations to Make the Array Elements Equal - Problem
Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps:
- Find the largest value in
nums. Let its index bei(0-indexed) and its value belargest. If there are multiple elements with the largest value, pick the smallesti. - Find the next largest value in
numsstrictly smaller thanlargest. Let its value benextLargest. - Reduce
nums[i]tonextLargest.
Return the number of operations to make all elements in nums equal.
Input & Output
Example 1 — Basic Reduction
$
Input:
nums = [5,1,3]
›
Output:
3
💡 Note:
Step by step: [5,1,3] → [3,1,3] → [1,1,3] → [1,1,1]. Total of 3 operations.
Example 2 — Already Equal
$
Input:
nums = [1,1,1]
›
Output:
0
💡 Note:
All elements are already equal, so no operations needed.
Example 3 — Multiple Same Values
$
Input:
nums = [1,1,2,2,3]
›
Output:
4
💡 Note:
[1,1,2,2,3] → [1,1,2,2,2] → [1,1,1,2,2] → [1,1,1,1,2] → [1,1,1,1,1]. Total of 4 operations.
Constraints
- 1 ≤ nums.length ≤ 5 × 104
- 1 ≤ nums[i] ≤ 5 × 104
Visualization
Tap to expand
Understanding the Visualization
1
Input
Array with different values: [5,1,3]
2
Reduction Process
Repeatedly reduce largest to next largest
3
Output
Count total operations needed: 3
Key Takeaway
🎯 Key Insight: Instead of simulating step by step, count frequencies and calculate operations mathematically by processing unique values in descending order.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code