Maximize number of days for which P chocolates can be distributed consecutively to N people | 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
var mp = new Map ( ) ; var N , P ; function helper ( mid ) { var cnt = 0 ; mp . forEach ( ( value , ) => { var temp = value ; while ( temp >= mid ) { temp -= mid ; cnt ++ ; } } ) ; return cnt >= N ; } function findMaximumDays ( arr ) { for ( var i = 0 ; i < P ; i ++ ) { if ( mp . has ( arr [ i ] ) ) mp . set ( arr [ i ] , mp . get ( arr [ i ] ) + 1 ) else mp . set ( arr [ i ] , 1 ) ; } var start = 0 , end = P , ans = 0 ; while ( start <= end ) { var mid = start + parseInt ( ( 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 ; } N = 3 , P = 10 ; var arr = [ 1 , 2 , 2 , 1 , 1 , 3 , 3 , 3 , 2 , 4 ] ; document . write ( findMaximumDays ( arr ) ) ;