Queries to count groups of N students possible having sum of ratings within given range | Function to count number of ways to get given sum groups ; Initialise dp array ; Mark all 1 st row values as 1 since the mat [ 0 ] [ i ] is all possible sums in first row ; Fix the ith row ; Fix the sum ; Iterate through all values of ith row ; If sum can be obtained ; Find the prefix sum of last row ; Traverse each query ; No of ways to form groups ; Given n batches and k students ; Given ratings ; Given Queries ; Function Call
function numWays ( ratings , queries ) { var dp = Array . from ( Array ( n ) , ( ) => Array ( 10002 ) . fill ( 0 ) ) ; for ( var i = 0 ; i < k ; i ++ ) dp [ 0 ] [ ratings [ 0 ] [ i ] ] += 1 ; for ( var i = 1 ; i < n ; i ++ ) { for ( var sum = 0 ; sum <= 10000 ; sum ++ ) { for ( var j = 0 ; j < k ; j ++ ) { if ( sum >= ratings [ i ] [ j ] ) dp [ i ] [ sum ] += dp [ i - 1 ] [ sum - ratings [ i ] [ j ] ] ; } } } for ( var sum = 1 ; sum <= 10000 ; sum ++ ) { dp [ n - 1 ] [ sum ] += dp [ n - 1 ] [ sum - 1 ] ; } for ( var q = 0 ; q < 2 ; q ++ ) { var a = queries [ q ] [ 0 ] ; var b = queries [ q ] [ 1 ] ; document . write ( dp [ n - 1 ] [ b ] - dp [ n - 1 ] [ a - 1 ] + " " ) ; } } var n = 2 ; var k = 3 ; var ratings = [ [ 1 , 2 , 3 ] , [ 4 , 5 , 6 ] ] ; var queries = [ [ 6 , 6 ] , [ 1 , 6 ] ] ; numWays ( ratings , queries ) ;