Minimum steps to make all the elements of the array divisible by 4 in C++


Problem statement

Given an array of size n, the task iss to find the minimum number of steps required to make all the elements of the array divisible by 4. A step is defined as removal of any two elements from the array and adding the sum of these elements to the array

Example

If input array is {1, 2, 0, 2, 4, 3} then 3 operations are required −

1 + 3 = 4
2 + 2 = 4
0 + 4 = 4

Algorithm

1. Sum of all the elements of the array should be divisible by If not, this task is not possible
2. Initialize an array namely modulus of size 4 to 0
3. Initialize a counter to 0. It will keep track of number of steps done
4. Traverse through the input array and take modulus 4 of each element
5. Increment the value of the mod 4 value in the modulus array by 1
6. modulus[0] is the count of elements that are already divisible by 4. So no need to pair them with any other element
7. modulus[1] and modulus[3] elements can be combined to get a number divisible by 4. So, increment count to the minimum value of the both
8. Every 2 elements of modulus[2] can be combined to get an element divisible to 4.
9. For the remaining elements, increment value modulus[2] by half of modulus[1] and modulus[3].
10. Now, increment count by half modulus[2]. We take half because every two elements are combined as one
11. The final value of count is the number of steps required to convert the all the elements of the input array divisible by 4

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int getMinRequiredSteps(int arr[], int n) {
   int count = 0;
   int modulus[4] = {0};
   int sum = 0;
   for (int i = 0; i < n; i++) {
      int mod = arr[i] % 4;
      sum += mod;
      modulus[mod]++;
   }
   if (sum % 4 != 0) {
      return -1;
   } else {
      if (modulus[1] > modulus[3]) {
         count += modulus[3];
      }
      else {
         count += modulus[1];
      }
      modulus[1] -= count;
      modulus[3] -= count;
      modulus[2] += modulus[1] / 2;
      modulus[2] += modulus[3] / 2;
      count += modulus[1] / 2;
      count += modulus[3] / 2;
      count += modulus[2] / 2;
      return count;
   }
}
int main() {
   int arr[] = {1, 2, 0, 2, 4, 3};
   int n = sizeof(arr) / sizeof(arr[0]);
   cout << "Minimum required steps = " << getMinRequiredSteps(arr, n) << endl;
   return 0;
}

When you compile and execute above program. It generates following output

Output

Minimum required steps = 2

Updated on: 23-Dec-2019

377 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements