Number of ways to choose elements from the array such that their average is K | javascript implementation of the above approach ; This dp array is used to store our values so that we don 't have to calculate same  values again and again ; Base cases Index can 't be less than 0 ; No element is picked hence average cannot be calculated ; If remainder is non zero , we cannot divide the sum by count i . e . the average will not be an integer ; If we find an average return 1 ; If we have already calculated this function simply return it instead of calculating it again ; If we don 't pick the current element  simple recur for index -1 ; If we pick the current element add it to our current sum and increment count by 1 ; Store the value for the current function ; Function to return the number of ways ; Push - 1 at the beginning to make it 1 - based indexing ; Initialize dp array by - 1 ; Call recursive function waysutil to calculate total ways ; Driver code
var MAX_INDEX = 51 ; var MAX_SUM = 2505 ; var dp = Array ( MAX_INDEX ) . fill ( ) . map ( ( ) => Array ( MAX_SUM ) . fill ( ) . map ( ( ) => Array ( MAX_INDEX ) . fill ( 0 ) ) ) ; ; function waysutil ( index , sum , count , arr , K ) { if ( index < 0 ) { return 0 ; } if ( index == 0 ) { if ( count == 0 ) { return 0 ; } var remainder = sum % count ; if ( remainder != 0 ) { return 0 ; } var average = sum / count ; if ( average == K ) { return 1 ; } } if ( dp [ index ] [ sum ] [ count ] != - 1 ) { return dp [ index ] [ sum ] [ count ] ; } var dontpick = waysutil ( index - 1 , sum , count , arr , K ) ; var pick = waysutil ( index - 1 , sum + arr [ index ] , count + 1 , arr , K ) ; var total = pick + dontpick ; dp [ index ] [ sum ] [ count ] = total ; return total ; } function ways ( N , K , arr ) { var Arr = [ ] ; Arr . push ( - 1 ) ; for ( i = 0 ; i < N ; ++ i ) { Arr . push ( arr [ i ] ) ; } for ( i = 0 ; i < MAX_INDEX ; i ++ ) { for ( j = 0 ; j < MAX_SUM ; j ++ ) { for ( l = 0 ; l < MAX_INDEX ; l ++ ) { dp [ i ] [ j ] [ l ] = - 1 ; } } } var answer = waysutil ( N , 0 , 0 , Arr , K ) ; return answer ; } var arr = [ 3 , 6 , 2 , 8 , 7 , 6 , 5 , 9 ] ; var N = arr . length ; var K = 5 ; document . write ( ways ( N , K , arr ) ) ;