text: Maximize number of days for which P chocolates can be distributed consecutively to N people | C ++ 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
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; map < int , int > mp ; int N , P ; bool helper ( int mid ) { int cnt = 0 ; for ( auto i : mp ) { int temp = i . second ; while ( temp >= mid ) { temp -= mid ; cnt ++ ; } } return cnt >= N ; } int findMaximumDays ( int arr [ ] ) { for ( int i = 0 ; i < P ; i ++ ) { mp [ arr [ i ] ] ++ ; } int start = 0 , end = P , ans = 0 ; while ( start <= end ) { int mid = start + ( ( end - start ) / 2 ) ; if ( mid != 0 and helper ( mid ) ) { ans = mid ; start = mid + 1 ; } else if ( mid == 0 ) { start = mid + 1 ; } else { end = mid - 1 ; } } return ans ; } int main ( ) { N = 3 , P = 10 ; int arr [ ] = { 1 , 2 , 2 , 1 , 1 , 3 , 3 , 3 , 2 , 4 } ; cout << findMaximumDays ( arr ) ; return 0 ; }