Maximize occurrences of values between L and R on sequential addition of Array elements with modulo H | Function that prlets the number of times X gets a value between L and R ; Base condition ; Condition if X can be made equal to j after i additions ; Compute value of X after adding arr [ i ] ; Compute value of X after adding arr [ i ] - 1 ; Update dp as the maximum value ; Compute maximum answer from all possible cases ; Printing maximum good occurrence of X ; Driver Code
function goodLeteger ( arr , n , h , l , r ) { let dp = new Array ( n + 1 ) ; for ( var i = 0 ; i < dp . length ; i ++ ) { dp [ i ] = new Array ( 2 ) ; } for ( let i = 0 ; i < n + 1 ; i ++ ) for ( let j = 0 ; j < h ; j ++ ) dp [ i ] [ j ] = - 1 ; dp [ 0 ] [ 0 ] = 0 ; for ( let i = 0 ; i < n ; i ++ ) { for ( let j = 0 ; j < h ; j ++ ) { if ( dp [ i ] [ j ] != - 1 ) { let h1 = ( j + arr [ i ] ) % h ; let h2 = ( j + arr [ i ] - 1 ) % h ; dp [ i + 1 ] [ h1 ] = Math . max ( dp [ i + 1 ] [ h1 ] , dp [ i ] [ j ] + ( ( h1 >= l && h1 <= r ) ? 1 : 0 ) ) ; dp [ i + 1 ] [ h2 ] = Math . max ( dp [ i + 1 ] [ h2 ] , dp [ i ] [ j ] + ( ( h2 >= l && h2 <= r ) ? 1 : 0 ) ) ; } } } let ans = 0 ; for ( let i = 0 ; i < h ; i ++ ) { if ( dp [ n ] [ i ] != - 1 ) ans = Math . max ( ans , dp [ n ] [ i ] ) ; } document . write ( ans + " " ) ; } let A = [ 16 , 17 , 14 , 20 , 20 , 11 , 22 ] ; let H = 24 ; let L = 21 ; let R = 23 ; let size = A . length ; goodLeteger ( A , size , H , L , R ) ;