Maximum sum of elements divisible by K from the given array | JavaScript program to implement the above approach ; Function to return the maximum sum divisible by k from elements of v ; check if sum of elements excluding the current one is divisible by k ; check if sum of elements including the current one is divisible by k ; Store the maximum ; Driver Code
let dp = new Array ( 1000 + 1 ) ; function find_max ( i , sum , v , k ) { if ( i == v . length ) return 0 ; if ( dp [ i ] [ sum ] != - 1 ) return dp [ i ] [ sum ] ; let ans = 0 ; if ( ( sum + find_max ( i + 1 , sum , v , k ) ) % k == 0 ) ans = find_max ( i + 1 , sum , v , k ) ; if ( ( sum + v [ i ] + find_max ( i + 1 , ( sum + v [ i ] ) % k , v , k ) ) % k == 0 ) ans = Math . max ( ans , v [ i ] + find_max ( i + 1 , ( sum + v [ i ] ) % k , v , k ) ) ; return dp [ i ] [ sum ] = ans ; } let arr = [ 43 , 1 , 17 , 26 , 15 ] ; let k = 16 ; for ( var i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( 2 ) ; } for ( var i = 0 ; i < dp . length ; i ++ ) { for ( var j = 0 ; j < dp . length ; j ++ ) { dp [ i ] [ j ] = - 1 ; } } document . write ( find_max ( 0 , 0 , arr , k ) ) ;