Similar Problems
Similar Problems not available
Make Array Zero By Subtracting Equal Amounts - Leetcode Solution
LeetCode: Make Array Zero By Subtracting Equal Amounts Leetcode Solution
Difficulty: Easy
Topics: greedy hash-table heap-priority-queue array sorting simulation
Problem Statement:
Given an integer array nums of length n, you want to make all the elements in the array equal. The only operation you can perform is subtracting an integer k (0 <= k <= 100) from any element in the array. Return the minimum number of operations to make all the elements in the array equal.
Example:
Input: nums = [2,4,6,8] Output: 4 Explanation: We can make all the elements equal to 4 by doing 4 operations: [2,4,6,8] -> [4,4,4,4].
Solution:
To make all the elements in the array equal, we need to first find the minimum element in the array. Then, we need to subtract the minimum element from all the elements in the array to make the minimum element equal to zero. Now, we need to find the sum of absolute values of all the elements in the array. This is the minimum number of operations required to make all the elements in the array equal.
Let's start by finding the minimum element in the array:
int minElement = INT_MAX;
for(int i=0;i<nums.size();i++){
minElement = min(minElement, nums[i]);
}
Now, let's subtract the minimum element from all the elements in the array:
for(int i=0;i<nums.size();i++){
nums[i] -= minElement;
}
Next, let's find the sum of absolute values of all the elements in the array:
int sum = 0;
for(int i=0;i<nums.size();i++){
sum += abs(nums[i]);
}
return sum;
The complete code implementation is as follows:
class Solution {
public:
int minOperations(vector<int>& nums) {
int minElement = INT_MAX;
for(int i=0;i<nums.size();i++){
minElement = min(minElement, nums[i]);
}
for(int i=0;i<nums.size();i++){
nums[i] -= minElement;
}
int sum = 0;
for(int i=0;i<nums.size();i++){
sum += abs(nums[i]);
}
return sum;
}
};
Make Array Zero By Subtracting Equal Amounts Solution Code
1