# Maximum number of trailing zeros in the product of the subsets of size k in C++

Given the task is to find the maximum number of trailing zeroes in the product of the subsets of size K, of a given array of size N.

Let’s now understand what we have to do using an example −

Input − Arr[] = {5, 20, 2} , K=2

Output − 2

Explanation − A total of 3 subsets can be created having size = 2.

The product of [5, 20] is 100.

The product of [20, 2] is 40.

The product of [5, 2] is 10.

100 has the maximum number of trailing zeros = 2. Therefore 2 is the answer.

Input − Arr[] = {60, 40, 25} , K=2

Output − 3

## Approach used in the below program as follows

• Before starting the functions, #define M5 100 on the top.

• In function MaxZeros() create a 2D array Sub[K + 1][M5 + 5] and initialize each of its value with -1 and set Sub = 0;

• Loop from P=0 till P<N and inside the loop initialize P2 = 0 and P5 = 0 both of type int which will be used to store the number of 2s and 5s in the given number respectively.

• Initiate a while loop with condition while(Arr[P]%2 == 0) and inside the loop do P2++ and Arr[P]/2 to obtain the number of 2s. Repeat the same step for P5.

• Then inside the above started For loop initialize two more nested for loops as follows −

for (int i = K - 1; i >= 0; i--)

for (int j = 0; j < M5; j++)

• Inside these loops check if(Sub[i][j] != -1) and if it is true then put Sub[i + 1][j + P5] = max(Sub[i + 1];[j + P5], Sub[i][j] + P2);

## Example

Live Demo

#include <bits/stdc++.h>
using namespace std;
#define M5 100
int MaxZeros(int* Arr, int N, int K){
//Initializing each value with -1;
int Sub[K+1][M5+5];
memset(Sub, -1, sizeof(Sub));
Sub = 0;
for (int P = 0; P < N; P++){
int P2 = 0, P5 = 0;
// Maximal power of 2 in Arr[P]
while (Arr[P] % 2 == 0){
P2++;
Arr[P] /= 2;
}
// Maximal power of 2 in Arr[P]
while (Arr[P] % 5 == 0) {
P5++;
Arr[P] /= 5;
}
/* We can collect 2s by checking first i numbers and taking their j with total power of 5*/
for (int i = K - 1; i >= 0; i--)
for (int j = 0; j < M5; j++)
// If subset[i][j] is not calculated.
if (Sub[i][j] != -1)
Sub[i + 1][j + P5] = max(Sub[i + 1][j + P5], Sub[i][j] + P2);
}
/* Taking minimum of 5 or 2 and maximizing the result*/
int ans = 0;
for (int i = 0; i < M5; i++)
ans = max(ans, min(i, Sub[K][i]));
return ans;
}
//Main function
int main(){
int Arr[] = { 60, 40, 25 };
int K = 2;
int N = sizeof(Arr) / sizeof(Arr);
cout << MaxZeros(Arr, N, K);
return 0;
}

## Output

If we run the above code we will get the following output −

3