Similar Problems

Similar Problems not available

Minimum Operations To Make All Array Elements Equal - Leetcode Solution

Companies:

LeetCode:  Minimum Operations To Make All Array Elements Equal Leetcode Solution

Difficulty: Medium

Topics: sorting prefix-sum binary-search array  

Problem Statement: You are given an integer array nums of length n. In one operation, you can perform the following:

Choose any index i (0-indexed) such that 0 <= i < n. Replace nums[i] with nums[i] + 1. Return the minimum number of operations needed to make all elements of nums equal.

Solution:

Approach: To make all elements of the array equal to some value x, we need to increment the elements, which are smaller than x to x and the elements which are greater than x to x. So, we count the number of operations required to do that.

Algorithm:

  1. Initialize 'ops' variable to 0, which will give us the count of operations required.

  2. Find the minimum element of the array.

  3. Iterate over the array and add the difference between each element and minimum element to the 'ops' variable.

  4. Return the 'ops' variable.

Time Complexity: O(n) Space Complexity: O(1)

Code:

class Solution { public: int minOperations(vector<int>& nums) { int ops = 0; int min_ele = *min_element(nums.begin(), nums.end()); for(int i=0; i<nums.size(); i++){ ops += (nums[i] - min_ele); } return ops; } };

Explanation:

  1. We have initialized the 'ops' variable to 0.

  2. We have found the minimum element of the array using the 'min_element()' function.

  3. We have iterated over the array and added the difference between each element and the minimum element to the 'ops' variable.

  4. Finally, we have returned the 'ops' variable.

Example:

Input: nums = [1,2,3] Output: 3 Explanation: We need to add 2 to 1 and 1 to 2 (total 3 operations) to make all elements of the array equal to 3.

Input: nums = [1,1,1] Output: 0 Explanation: All elements of the array are already equal, so no operation is required.

Minimum Operations To Make All Array Elements Equal Solution Code

1