Maximum number of groups that can receive fresh donuts distributed in batches of size K | Java program for the above approach ; Recursive function to find the maximum number of groups that will receive fresh donuts ; Store the result for the current state ; Check if the leftover donuts from the previous batch is 0 ; If true , then one by one give the fresh donuts to each group ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] ; Otherwise , traverse the given array , arr [ ] ; Decrement arr [ i ] ; Update the maximum number of groups ; Increment arr [ i ] ; Return the value of q ; Function to find the maximum number of groups that will receive fresh donuts ; Stores count of remainder by K ; Traverse the array arr [ ] ; Stores maximum number of groups ; Return the answer ; Driver Code
import java . io . * ; import java . util . * ; class GFG { public static int dfs ( int [ ] arr , int left , int K ) { int q = 0 ; if ( left == 0 ) { for ( int i = 1 ; i < K ; ++ i ) { if ( arr [ i ] > 0 ) { arr [ i ] -- ; q = Math . max ( q , 1 + dfs ( arr , K - i , K ) ) ; arr [ i ] ++ ; } } } else { for ( int i = 1 ; i < K ; ++ i ) { if ( arr [ i ] > 0 ) { arr [ i ] -- ; int nleft = ( i <= left ? left - i : K + left - i ) ; q = Math . max ( q , dfs ( arr , nleft , K ) ) ; arr [ i ] ++ ; } } } return q ; } public static int maxGroups ( int K , int [ ] arr ) { int V [ ] = new int [ K ] ; for ( int x : arr ) V [ x % K ] ++ ; int ans = V [ 0 ] + dfs ( V , 0 , K ) ; return ans ; } public static void main ( String [ ] args ) { int [ ] arr = { 1 , 2 , 3 , 4 , 5 , 6 } ; int K = 3 ; System . out . println ( maxGroups ( K , arr ) ) ; } }