Similar Problems

Similar Problems not available

Minimum Number Of Operations To Make All Array Elements Equal To 1 - Leetcode Solution

Companies:

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

Difficulty: Medium

Topics: math array  

Problem Statement:

Given an integer array nums of size n, return the minimum number of moves required to make all array elements equal.

In one move, you can increment or decrement an element of the array by 1.

Example: Input: nums = [1,2,3] Output: 2 Explanation: Only two moves are needed (remember each move increments or decrements one element): [1,2,3] => [2,2,3] => [2,2,2]

Solution:

The solution to this problem can be achieved in multiple ways, however, the most optimized way of solving this problem is to use the mathematical formula approach.

The mathematical formula to find the minimum number of moves is to find the sum of the absolute difference of all elements of an array and the minimum element of that array.

Step 1: Find the minimum element of the given array.

Step 2: Compute the sum of the absolute difference between each array element and the minimum element.

Step 3: Return the sum of the absolute difference computed in the previous step.

Python code:

class Solution: def minMoves(self, nums: List[int]) -> int:

    # Finding Minimum element in the array
    min_element = min(nums)
    
    # Calculating the sum of absolute difference between each element and minimum element
    sum_moves = sum([abs(num - min_element) for num in nums])
    
    # Returning the minimum number of moves to make all elements equal to 1
    return sum_moves

Time Complexity: O(n)

Space Complexity: O(1)

Minimum Number Of Operations To Make All Array Elements Equal To 1 Solution Code

1