Similar Problems
Similar Problems not available
Reduction Operations To Make The Array Elements Equal - Leetcode Solution
Companies:
LeetCode: Reduction Operations To Make The Array Elements Equal Leetcode Solution
Difficulty: Medium
Problem Statement:
Given an integer array nums, your goal is to make all elements in nums equal. To perform one reduction operation, you can choose two elements nums[i] and nums[j] where 1 <= i, j <= n (n is the length of nums) and reduce nums[i] or nums[j] by one. The goal is to minimize the number of reduction operations required to make all elements in nums equal.
Example:
Input: nums = [5, 3, 1]
Output: 3
Explanation:
We can perform the following reduction operations:
- Reduce nums[0] and nums[1] by 2: [3, 1, 1]
- Reduce nums[0] and nums[2] by 2: [1, 1, 1]
After three reduction operations, all elements in nums become equal to 1.
Solution:
Approach:
The problem can be solved by calculating the median of the array. The goal is to bring all elements closer to the median. We can then calculate the absolute difference between each element and the median. The sum of all such differences will give us the minimum number of reduction operations required to make all elements in the array equal.
Steps:
-
Calculate the median of the array - sum all elements and divide by the length of the array. If the sum is not divisible by the length, we can take the floor or ceil value of the division, depending on the value of the remainder.
-
Calculate the absolute difference between each element and the median.
-
Sum all such differences and return the result.
Pseudocode:
- Initialize sum = 0
- Sort the array nums in non-decreasing order
- Calculate the median: a. Calculate the sum of all elements in nums: sum(nums) b. Divide sum by the length of nums: sum(nums) / len(nums) c. If sum(nums) is not divisible by len(nums), round the division to the nearest integer value: round(sum(nums) / len(nums))
- Iterate through nums: a. Add the absolute difference between each element and the median to sum: sum += abs(nums[i] - median)
- Return sum
Python Code:
class Solution: def minMoves2(self, nums: List[int]) -> int: nums.sort() n = len(nums) median = 0
# calculate median
if n % 2 == 0:
median = (nums[(n-1)//2] + nums[(n+1)//2]) // 2
else:
median = nums[n//2]
# calculate sum of absolute differences between each element and the median
sum_diff = 0
for num in nums:
sum_diff += abs(num - median)
return sum_diff
Reduction Operations To Make The Array Elements Equal Solution Code
1