3190. Find Minimum Operations to Make All Elements Divisible by Three #2450
-
|
Topics: You are given an integer array Return the minimum number of operations to make all elements of Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
|
We need to make all elements divisible by 3 with minimum operations, where each operation is adding or subtracting 1. For any number, there are three possible cases:
So for each number, the minimum operations needed is simply the minimum distance to the nearest multiple of 3, which can be calculated as Let's implement this solution in PHP: 3190. Find Minimum Operations to Make All Elements Divisible by Three <?php
/**
* @param Integer[] $nums
* @return Integer
*/
function minimumOperations($nums) {
$operations = 0;
foreach ($nums as $num) {
$remainder = $num % 3;
$operations += min($remainder, 3 - $remainder);
}
return $operations;
}
// Test cases
echo minimumOperations([1,2,3,4]) . "\n"; // Output: 3
echo minimumOperations([3,6,9]) . "\n"; // Output: 0
?>Explanation:
Time Complexity: O(n) - we iterate through the array once |
Beta Was this translation helpful? Give feedback.
We need to make all elements divisible by 3 with minimum operations, where each operation is adding or subtracting 1.
For any number, there are three possible cases:
So for each number, the minimum operations needed is simply the minimum distance to the nearest multiple of 3, which can be calculated as
min(num % 3, 3 - (num % 3)).Let's implement this solution in PHP: 3190. Find Minimum Operations to Make All Elements Divisible by Three