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
nums
strictly smaller thanlargest
. Let its value benextLargest
. - Reduce
nums[i]
tonextLargest
.
Return the number of operations to make all elements in nums
equal.
Example 1:
Input: nums = [5,1,3] Output: 3 Explanation: It takes 3 operations to make all elements in nums equal: 1. largest = 5 at index 0. nextLargest = 3. Reduce nums[0] to 3. nums = [3,1,3]. 2. largest = 3 at index 0. nextLargest = 1. Reduce nums[0] to 1. nums = [1,1,3]. 3. largest = 3 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1].
Example 2:
Input: nums = [1,1,1] Output: 0 Explanation: All elements in nums are already equal.
Example 3:
Input: nums = [1,1,2,2,3] Output: 4 Explanation: It takes 4 operations to make all elements in nums equal: 1. largest = 3 at index 4. nextLargest = 2. Reduce nums[4] to 2. nums = [1,1,2,2,2]. 2. largest = 2 at index 2. nextLargest = 1. Reduce nums[2] to 1. nums = [1,1,1,2,2]. 3. largest = 2 at index 3. nextLargest = 1. Reduce nums[3] to 1. nums = [1,1,1,1,2]. 4. largest = 2 at index 4. nextLargest = 1. Reduce nums[4] to 1. nums = [1,1,1,1,1].
Constraints:
1 <= nums.length <= 5 * 104
1 <= nums[i] <= 5 * 104
Companies: Microsoft
Related Topics:
Array, Sorting
Hints:
- Sort the array.
- Try to reduce all elements with maximum value to the next maximum value in one operation.
// OJ: https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(N)
class Solution {
public:
int reductionOperations(vector<int>& A) {
map<int, int> m;
for (int n : A) m[n]++;
int step = 0, ans = 0;
for (auto &[n, cnt] : m) {
if (step > 0) ans += cnt * step;
++step;
}
return ans;
}
};
// OJ: https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal/
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
int reductionOperations(vector<int>& A) {
sort(begin(A), end(A));
int N = A.size(), step = 0, ans = 0;
for (int i = 1; i < N; ++i) {
if (A[i] != A[i - 1]) ++step;
ans += step;
}
return ans;
}
};
Or
// OJ: https://leetcode.com/problems/reduction-operations-to-make-the-array-elements-equal
// Author: github.com/lzl124631x
// Time: O(NlogN)
// Space: O(1)
class Solution {
public:
int reductionOperations(vector<int>& A) {
sort(begin(A), end(A));
int ans = 0, N = A.size(), i = 0;
while (i < N && A[i] == A[0]) ++i;
for (; i < N; ++i) {
ans += N - i;
while (i + 1 < N && A[i + 1] == A[i]) ++i;
}
return ans;
}
};