Maximize occurrences of values between L and R on sequential addition of Array elements with modulo H | C # implementation of the above approach ; Function that prints 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
using System ; class GFG { static void goodint ( int [ ] arr , int n , int h , int l , int r ) { int [ , ] dp = new int [ n + 1 , h ] ; for ( int i = 0 ; i < n ; i ++ ) for ( int j = 0 ; j < h ; j ++ ) dp [ i , j ] = - 1 ; dp [ 0 , 0 ] = 0 ; for ( int i = 0 ; i < n ; i ++ ) { for ( int j = 0 ; j < h ; j ++ ) { if ( dp [ i , j ] != - 1 ) { int h1 = ( j + arr [ i ] ) % h ; int 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 ) ) ; } } } int ans = 0 ; for ( int i = 0 ; i < h ; i ++ ) { if ( dp [ n , i ] != - 1 ) ans = Math . Max ( ans , dp [ n , i ] ) ; } Console . Write ( ans + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { int [ ] A = { 16 , 17 , 14 , 20 , 20 , 11 , 22 } ; int H = 24 ; int L = 21 ; int R = 23 ; int size = A . Length ; goodint ( A , size , H , L , R ) ; } }