Dare2Solve
The problem requires making all elements of the array divisible by 3 using the minimum number of operations. Each operation allows us to either add or subtract 1 from any element, making it possible to adjust elements until they become divisible by 3.
The key insight is to recognize that any integer can be one of three possible remainders when divided by 3: 0, 1, or 2. The goal is to convert every element of the array such that it has a remainder of 0 when divided by 3. This can be achieved by:
operations
to count the total number of operations required.operations
counter by 1 (since subtracting 1 will make it divisible by 3).operations
counter by 1 (since adding 1 will make it divisible by 3).operations
.This approach ensures that we handle each element independently, adjusting it to meet the requirement efficiently.
class Solution {
public:
int minimumOperations(std::vector<int>& nums) {
int count = 0;
for (int num : nums) {
if (num % 3 != 0) {
count++;
}
}
return count;
}
};
class Solution:
def minimumOperations(self, nums: List[int]) -> int:
return sum(1 for num in nums if num % 3 != 0)
cpublic class Solution {
public int minimumOperations(int[] nums) {
int count = 0;
for (int num : nums) {
if (num % 3 != 0) {
count++;
}
}
return count;
}
}
/**
* @param {number[]} nums
* @return {number}
*/
var minimumOperations = function (nums) {
return nums.reduce((a, b) => a + (b % 3 !== 0), 0);
};
func minimumOperations(nums []int) int {
count := 0
for _, num := range nums {
if num % 3 != 0 {
count++
}
}
return count
}
public class Solution {
public int MinimumOperations(int[] nums) {
int count = 0;
foreach (int num in nums) {
if (num % 3 != 0) {
count++;
}
}
return count;
}
}