#3190
Easy Algorithms Find minimum operations to make all elements divisible by three
Array Math
90.9% acceptance
Feb 24, 2026
510
34
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.
Solution
Rust
Time O(n)
Space O(1)
impl Solution {
pub fn minimum_operations(nums: Vec<i32>) -> i32 {
nums.iter().map(|&x| {
let r = x % 3;
r.min(3 - r)
}).sum()
}
}