Find maximum subset | C ++ 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumSum ( vector < 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 ) { sum += A [ j ] ; c ++ ; } } if ( sum % D == 0 && c <= K ) ans = max ( ans , sum ) ; } return ans ; } int main ( ) { int N = 5 , K = 3 , D = 7 ; vector < int > A = { 1 , 11 , 5 , 5 , 18 } ; cout << maximumSum ( A , N , K , D ) << endl ; return 0 ; }