Leetcode 3190. Find Minimum Operations to Make All Elements Divisible by Three
You are given an array nums
of size n
. You can perform the following operation on the array any number of times:
i
and j
, and set nums[i]
to nums[i] + nums[j]
.You need to determine the minimum number of operations required to make all elements of the array divisible by 3.
nums
? (e.g., range of values)n
?nums
be negative or zero?#include <iostream>
#include <vector>
using namespace std;
int minOperationsToMakeDivisibleByThree(vector<int>& nums) {
int count_mod1 = 0, count_mod2 = 0;
for (int num : nums) {
if (num % 3 == 1) {
count_mod1++;
} else if (num % 3 == 2) {
count_mod2++;
}
}
if (count_mod1 == 0 && count_mod2 == 0) {
return 0; // All numbers are already divisible by 3
}
if (count_mod1 == count_mod2) {
return count_mod1;
}
return max(count_mod1, count_mod2);
}
int main() {
vector<int> nums = {2, 2, 5, 8};
cout << minOperationsToMakeDivisibleByThree(nums) << endl;
return 0;
}
1
or 2
when divided by 3.1
and no numbers with a remainder of 2
, the array is already in the desired state.1
and 2
are equal, each pair can solve each other.n
is the length of the array.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?