Largest number with the given set of N digits that is divisible by 2 , 3 and 5 | Java 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
import java . util . * ; class GFG { static int findLargest ( int n , Vector < Integer > v ) { int flag = 0 ; long sum = 0 ; for ( int i = 0 ; i < n ; i ++ ) { if ( v . get ( i ) == 0 ) flag = 1 ; sum += v . get ( i ) ; } if ( flag != 1 ) System . out . println ( " Not ▁ possible " ) ; else { Collections . sort ( v , Collections . reverseOrder ( ) ) ; if ( v . get ( 0 ) == 0 ) { System . out . println ( "0" ) ; return 0 ; } else { int flags = 0 ; int y = ( int ) ( sum % 3 ) ; if ( y != 0 ) { for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( v . get ( i ) % 3 == y ) { v . remove ( i ) ; flags = 1 ; break ; } } if ( flags == 0 ) { y = 3 - y ; int cnt = 0 ; for ( int i = n - 1 ; i >= 0 ; i -- ) { if ( v . get ( i ) % 3 == y ) { v . remove ( i ) ; cnt ++ ; if ( cnt >= 2 ) break ; } } } } if ( v . get ( 0 ) == 0 ) System . out . println ( "0" ) ; else for ( Integer i : v ) { System . out . print ( i ) ; } } } return Integer . MIN_VALUE ; } public static void main ( String [ ] args ) { int arr [ ] = { 3 , 9 , 9 , 6 , 4 , 3 , 6 , 4 , 9 , 6 , 0 } ; int n = 11 ; Vector < Integer > v = new Vector < Integer > ( ) ; for ( int i = 0 ; i < n ; i ++ ) v . add ( i , arr [ i ] ) ; findLargest ( n , v ) ; } }