You are given an integer array nums. In one operation, you can add or subtract 1 from any element of nums.
Return the minimum number of operations to make all elements of nums divisible by 3.
Example 1:
Input: nums = [1,2,3,4]
Output: 3
Explanation:
All array elements can be made divisible by 3 using 3 operations:
Example 2:
Input: nums = [3,6,9]
Output: 0
Constraints:
1 <= nums.length <= 501 <= nums[i] <= 50This approach involves iterating through the array and checking the remainder when each element is divided by 3.
Count these operations and sum them up to get the total minimum operations required.
The solution loops through each number, checks its remainder when divided by 3, and adjusts the operation count based on whether the remainder is 1 or 2. The function returns the sum of all adjustments needed.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n) where n is the number of elements in nums.
Space Complexity: O(1) as we are using a constant amount of space.
This approach counts how many numbers in the array have remainders of 1 or 2, thus directly determining the operations needed without checking each element individually in a loop, leveraging the properties of remainders.
Keep count of numbers with remainders 1 and 2, which directly translates to required operations.
C++
Java
Python
C#
JavaScript
Time Complexity: O(n)
Space Complexity: O(1)
| Approach | Complexity |
|---|---|
| Approach 1: Modulo and Adjustment | Time Complexity: O(n) where n is the number of elements in nums. |
| Approach 2: Array to Direct Count | Time Complexity: O(n) |
How to EASILY solve LeetCode problems • NeetCode • 427,763 views views
Watch 9 more video solutions →Practice Find Minimum Operations to Make All Elements Divisible by Three with our built-in code editor and test cases.
Practice on FleetCode