For each number, I only care about its remainder mod 3:
- If num % 3 == 0, cost = 0 (already divisible).
- If num % 3 == 1, I can subtract 1 → cost = 1.
- If num % 3 == 2, I can add 1 → cost = 1.
Since adding/subtracting 1 always brings the number directly to a multiple of 3, every non-divisible number costs exactly 1 operation. So I simply count how many numbers have remainder 1 or 2.
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
ans = 0
for x in nums:
if x % 3 != 0:
ans += 1
return ans- Time: O(n)
- Space: O(1)