I observe that each decrement reduces the total sum by exactly 1. Let r = sum(nums) % k be the remainder we need to remove to make the sum divisible by k. I can always perform exactly r single-unit decrements across the elements (never needing any fancy distribution beyond reducing the total by r), so the minimum number of operations is r. If r == 0 no operations are needed.
class Solution:
def minOperations(self, nums: List[int], k: int) -> int:
total = sum(nums)
return total % k- Time: O(n)
- Space: O(1)