Find maximum subset | Java program for tha above approach ; Function to calculate maximum sum possible by taking at most K elements that is divisibly by D ; Variable to store final answer ; Traverse all subsets ; Update ans if necessary conditions are satisfied ; Driver Code ; Input ; Function call
import java . util . * ; class GFG { static int maximumSum ( int [ ] A , int N , int K , int D ) { int ans = 0 ; for ( int i = 0 ; i < ( 1 << N ) ; i ++ ) { int sum = 0 ; int c = 0 ; for ( int j = 0 ; j < N ; j ++ ) { if ( ( i >> j & 1 ) != 0 ) { sum += A [ j ] ; c ++ ; } } if ( sum % D == 0 && c <= K ) ans = Math . max ( ans , sum ) ; } return ans ; } public static void main ( String [ ] args ) { int N = 5 , K = 3 , D = 7 ; int [ ] A = { 1 , 11 , 5 , 5 , 18 } ; System . out . print ( maximumSum ( A , N , K , D ) ) ; } }