[LeetCode] Reduction Operations to Make the Array Elements Equal

1887. Reduction Operations to Make the Array Elements Equal

Given an integer array nums, your goal is to make all elements in nums equal. To complete one operation, follow these steps:

  1. Find the largest value in nums. Let its index be i (0-indexed) and its value be largest. If there are multiple elements with the largest value, pick the smallest i.
  2. Find the next largest value in nums strictly smaller than largest. Let its value be nextLargest.
  3. Reduce nums[i] to nextLargest.

Return the number of operations to make all elements in nums equal.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public:
int reductionOperations(vector<int>& A) {
sort(begin(A), end(A));
int res = 0, n = A.size(), i = n - 1;
while(i > 0) {
while(i and A[i] == A[i-1]) i--;
if(i)
res += n - i;
i--;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/07/07/PS/LeetCode/reduction-operations-to-make-the-array-elements-equal/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.