text: Minimize K to let Person A consume at least ceil ( N / ( M + 1 ) ) candies based on given rules | C ++ program for the above approach ; Function to check if the value of mid gives at least ( N / ( M + 1 ) ) candies or not ; Candies taken by 1 st person is minimum of K and candies left ; Traverse the given array ; Amount consumed by person j ; Update the count of candies ; Check if person 1 gets the good share of candies ; Function to find minimum value of K such that the first person gets at least ( N / ( M + 1 ) ) candies ; Find the minimum required value of candies for the first person ; Iterate until low is less than or equal to mid ; Find the value of mid ; Check for mid , whether it can be the possible value of K or not ; Update the value of hi ; Otherwise , update the value of lo ; Print the resultant minimum value of K ; Driver Code
code: #include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int K , int n , int m , vector < int > arr , int good_share ) { int candies = n , taken = 0 ; while ( candies > 0 ) { taken += min ( K , candies ) ; candies -= min ( K , candies ) ; for ( int j = 0 ; j < m ; j ++ ) { int consume = ( arr [ j ] * candies ) / 100 ; candies -= consume ; } } return ( taken >= good_share ) ; } void minimumK ( vector < int > & arr , int N , int M ) { int good_share = ceil ( ( N * 1.0 ) / ( ( M + 1 ) * 1.0 ) ) ; int lo = 1 , hi = N ; while ( lo < hi ) { int mid = ( lo + hi ) / 2 ; if ( check ( mid , N , M , arr , good_share ) ) { hi = mid ; } else { lo = mid + 1 ; } } cout << hi ; } int main ( ) { int N = 13 , M = 1 ; vector < int > arr = { 50 } ; minimumK ( arr , N , M ) ; return 0 ; }