Maximize number of days for which P chocolates can be distributed consecutively to N people | Java program to implement the above approach ; Stores the frequency of each type of chocolate ; Function to check if chocolates can be eaten for ' mid ' no . of days ; If cnt exceeds N , return true ; Function to find the maximum number of days for which chocolates can be eaten ; Store the frequency of each type of chocolate ; Initialize start and end with 0 and P respectively ; Calculate mid ; Check if chocolates can be distributed for mid days ; Check if chocolates can be distributed for more than mid consecutive days ; Driver code ; Function call
import java . util . * ; class GFG { static HashMap < Integer , Integer > mp = new HashMap < Integer , Integer > ( ) ; static int N , P ; static boolean helper ( int mid ) { int cnt = 0 ; for ( Map . Entry < Integer , Integer > i : mp . entrySet ( ) ) { int temp = i . getValue ( ) ; while ( temp >= mid ) { temp -= mid ; cnt ++ ; } } return cnt >= N ; } static int findMaximumDays ( int arr [ ] ) { for ( int i = 0 ; i < P ; i ++ ) { if ( mp . containsKey ( arr [ i ] ) ) { mp . put ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) ; } else { mp . put ( arr [ i ] , 1 ) ; } } int start = 0 , end = P , ans = 0 ; while ( start <= end ) { int mid = start + ( ( end - start ) / 2 ) ; if ( mid != 0 && helper ( mid ) ) { ans = mid ; start = mid + 1 ; } else if ( mid == 0 ) { start = mid + 1 ; } else { end = mid - 1 ; } } return ans ; } public static void main ( String [ ] args ) { N = 3 ; P = 10 ; int arr [ ] = { 1 , 2 , 2 , 1 , 1 , 3 , 3 , 3 , 2 , 4 } ; System . out . print ( findMaximumDays ( arr ) ) ; } }