Largest number with the given set of N digits that is divisible by 2 , 3 and 5 | C ++ implementation of above approach ; Function to find the largest integer with the given set ; find sum of all the digits look if any 0 is present or not ; if 0 is not present , the resultant number won 't be divisible by 5 ; sort all the elements in a non - decreasing manner ; if there is just one element 0 ; find the remainder of the sum of digits when divided by 3 ; there can a remainder as 1 or 2 ; traverse from the end of the digits ; first element which has the same remainder remove it ; if there is no element which has a same remainder as y ; subtract it by 3 ( could be one or two ) ; delete two minimal digits which has a remainder as y ; print all the digits as a single integer ; Driver code ; initialize the number of set of digits ; initialize all the set of digits in a vector
#include <bits/stdc++.h> NEW_LINE using namespace std ; #define ll  long long NEW_LINE int findLargest ( int n , vector < int > & v ) { int flag = 0 ; ll sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( v [ i ] == 0 ) flag = 1 ; sum += v [ i ] ; } if ( ! flag ) cout << " Not ▁ possible " << endl ; else { sort ( v . begin ( ) , v . end ( ) , greater < int > ( ) ) ; if ( v [ 0 ] == 0 ) { cout << "0" << endl ; return 0 ; } else { int flag = 0 ; int y = sum % 3 ; if ( y != 0 ) { for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( v [ i ] % 3 == y ) { v . erase ( v . begin ( ) + i ) ; flag = 1 ; break ; } } if ( flag == 0 ) { y = 3 - y ; int cnt = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( v [ i ] % 3 == y ) { v . erase ( v . begin ( ) + i ) ; cnt ++ ; if ( cnt >= 2 ) break ; } } } } if ( * v . begin ( ) == 0 ) cout << "0" << endl ; else for ( int i : v ) { cout << i ; } } } } int main ( ) { int n = 11 ; vector < int > v { 3 , 9 , 9 , 6 , 4 , 3 , 6 , 4 , 9 , 6 , 0 } ; findLargest ( n , v ) ; return 0 ; }