Find Minimum Operations to Make All Elements Divisible by Three

You are given an integer array nums. In one operation you can add 1 to or subtract 1 from any element. Return the minimum number of operations needed to make every element divisible by 3.

30:00

Find Minimum Operations to Make All Elements Divisible by Three
easy
Free written solution
Topics
Companies

You are given an integer array nums. In one operation you can add 1 to or subtract 1 from any element. Return the minimum number of operations needed to make every element divisible by 3.

Example 1:
Input: {"nums":[1,2,3,4]}
Output: 3
Constraints:
  • 1≤1 \leq nums.length ≤50\leq 50

  • 1≤1 \leq nums[i] ≤50\leq 50

Test Cases
Input (Stdin)
Expected Output (Stdout)
Execution Result

Run code to see results.

Input
arr ={"nums":[1,2,3,4]}

Every integer is at most one step from a multiple of 3: remainder 1 steps down, remainder 2 steps up, remainder 0 is already done.

nums and the nudge each one needs

1

2

3

4

✓ remainder 0

−1 remainder 1

+1 remainder 2

where it sits between multiples of 3

Multiples of 3 are spaced 3 apart, so any number has one within distance 1.

ops

0

Variables
VariableValue
ops0
DepthFunction Call
Stack empty
0/6