Problem Description
Given an integer array nums, the task is to make all elements equal by repeatedly performing the following operation: identify the largest element (choosing the smallest index if there are ties), then reduce this element to the next largest value that is strictly smaller. Return the total number of operations required to make every element in nums equal.
Key Insights
- Sorting the array simplifies the identification of distinct values.
- The smallest element in the sorted array is the final target value.
- Each distinct value (from smallest to largest) contributes operations equal to the number of elements that are above that value.
- Rather than simulating each operation, count the reductions needed by iterating through the sorted array and accumulating a running count of distinct values encountered.
Space and Time Complexity
Time Complexity: O(n log n) due to sorting. Space Complexity: O(n) if the sorting algorithm requires extra space; O(1) additional space if an in-place sort is used.
Solution
The solution starts by sorting the array in ascending order. Once sorted, the smallest element is the target value for all elements. For each element starting from the second one, we check if it is different from the previous element. If so, a new distinct (larger) value is found, and we increment a counter representing the number of distinct values encountered so far. Each element will eventually have to be reduced as many times as the number of distinct values that are less than it. By summing these counts, we obtain the total number of operations required. This method efficiently calculates the answer without simulating the individual reduction operations.