Skip to content

1887. Reduction Operations to Make the Array Elements Equal 👍

  • Time: $O(\texttt{sort})$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
class Solution {
 public:
  int reductionOperations(vector<int>& nums) {
    int ans = 0;

    ranges::sort(nums);

    for (int i = nums.size() - 1; i > 0; --i)
      if (nums[i] != nums[i - 1])
        ans += nums.size() - i;

    return ans;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution {
  public int reductionOperations(int[] nums) {
    int ans = 0;

    Arrays.sort(nums);

    for (int i = nums.length - 1; i > 0; --i)
      if (nums[i] != nums[i - 1])
        ans += nums.length - i;

    return ans;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class Solution:
  def reductionOperations(self, nums: list[int]) -> int:
    ans = 0

    nums.sort()

    for i in range(len(nums) - 1, 0, -1):
      if nums[i] != nums[i - 1]:
        ans += len(nums) - i

    return ans