Similar Problems

Similar Problems not available

Minimum Operations To Halve Array Sum - Leetcode Solution

Companies:

LeetCode:  Minimum Operations To Halve Array Sum Leetcode Solution

Difficulty: Medium

Topics: greedy heap-priority-queue array  

Problem Statement:

Given an integer array nums of length n, you want to make the sum of the elements in nums divisible by n.

Return the minimum number of moves required to make the sum of nums divisible by n.

A move consists of choosing any element of nums and adding it to another element.

Solution:

To solve this problem, we first need to find the sum of all elements in the array. Let's call this sum as "arr_sum". We then need to find the remainder of arr_sum when divided by n. If the remainder is 0, then we don't need to do any moves as the sum is already divisible by n. If the remainder is r, then we need to make arr_sum+r divisible by n.

To make arr_sum+r divisible by n, we can add arr_sum % n to each element in the array. This is because adding arr_sum % n to each element will not change the remainder of arr_sum when divided by n. For example, if arr_sum % n = 2, then adding 2 to each element will make the sum of the array divisible by n.

However, adding arr_sum % n to each element may not result in the minimum number of moves required to make the sum of nums divisible by n. To minimize the number of moves, we need to add arr_sum % n to the smallest k elements in the array (where k is the remainder of arr_sum when divided by n). This is because adding arr_sum % n to smaller elements will result in a smaller increase in the sum of the array compared to adding it to larger elements.

Thus, the minimum number of moves required to make the sum of nums divisible by n is the sum of the differences between each element and the new sum (i.e., (arr_sum+r)/n) after adding arr_sum % n to the smallest k elements in the array.

Code:

Here is the Python code to solve this problem:

class Solution: def minMoves(self, nums: List[int]) -> int: arr_sum = sum(nums) n = len(nums) r = arr_sum % n

    if r == 0:
        return 0
    
    nums.sort()
    moves = 0
    for i in range(r):
        moves += (arr_sum + r) // n - nums[i]
    
    return moves

Time Complexity:

The time complexity of this solution is O(nlogn), where n is the length of the input array. This is because we first need to sort the array, which takes O(nlogn) time. We then need to iterate through the smallest k elements in the array (where k is the remainder of arr_sum when divided by n), which takes O(k) time (which is O(n) in the worst case). Finally, we need to perform a few arithmetic operations, which take constant time.

Space Complexity:

The space complexity of this solution is O(1), as we do not use any extra space other than a few variables.

Minimum Operations To Halve Array Sum Solution Code

1