Given an array of integers nums
, find the minimum number of operations required to make all elements divisible by 3. In one operation, you can increase or decrease an element of the array by 1.
nums
?
nums
?
x
, if x % 3 == 0
, it is already divisible by 3.x % 3 == 1
, we need 2 steps to make x
divisible by 3 (either -1 or +2).x % 3 == 2
, we need 1 step to make x
divisible by 3 (either +1 or -2).x % 3 == 1
* 2 + count of x % 3 == 2
.def min_operations_to_divisible_by_3(nums):
remainder_1_count = 0
remainder_2_count = 0
for num in nums:
remainder = num % 3
if remainder == 1:
remainder_1_count += 1
elif remainder == 2:
remainder_2_count += 1
operations = remainder_1_count * 2 + remainder_2_count
return operations
# Example usage
nums = [1, 2, 3, 4]
print(min_operations_to_divisible_by_3(nums)) # Output should be 3
The time complexity of this solution is (O(n)), where (n) is the length of the array. This is because we are making a single pass over the array to count the remainders, and the operations required for each element are performed in constant time.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?