Number of ways to choose elements from the array such that their average is K | Python implementation of above approach ; Initialize dp array by - 1 ; 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 ; Call recursive function waysutil to calculate total ways ; Driver code
import numpy as np NEW_LINE MAX_INDEX = 51 NEW_LINE MAX_SUM = 2505 NEW_LINE dp = np . ones ( ( MAX_INDEX , MAX_SUM , MAX_INDEX ) ) * - 1 ; NEW_LINE def waysutil ( index , sum , count , arr , K ) : NEW_LINE INDENT if ( index < 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT if ( index == 0 ) : NEW_LINE INDENT if ( count == 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT remainder = sum % count ; NEW_LINE if ( remainder != 0 ) : NEW_LINE INDENT return 0 ; NEW_LINE DEDENT average = sum // count ; NEW_LINE if ( average == K ) : NEW_LINE INDENT return 1 ; NEW_LINE DEDENT DEDENT if ( dp [ index ] [ sum ] [ count ] != - 1 ) : NEW_LINE INDENT return dp [ index ] [ sum ] [ count ] ; NEW_LINE DEDENT dontpick = waysutil ( index - 1 , sum , count , arr , K ) ; NEW_LINE pick = waysutil ( index - 1 , sum + arr [ index ] , count + 1 , arr , K ) ; NEW_LINE total = pick + dontpick ; NEW_LINE dp [ index ] [ sum ] [ count ] = total ; NEW_LINE return total ; NEW_LINE DEDENT def ways ( N , K , arr ) : NEW_LINE INDENT Arr = [ ] ; NEW_LINE Arr . append ( - 1 ) ; NEW_LINE for i in range ( N ) : NEW_LINE INDENT Arr . append ( arr [ i ] ) ; NEW_LINE DEDENT answer = waysutil ( N , 0 , 0 , Arr , K ) ; NEW_LINE return answer ; NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT arr = [ 3 , 6 , 2 , 8 , 7 , 6 , 5 , 9 ] ; NEW_LINE N = len ( arr ) ; NEW_LINE K = 5 ; NEW_LINE print ( ways ( N , K , arr ) ) ; NEW_LINE DEDENT