Minimize K to let Person A consume at least ceil ( N / ( M + 1 ) ) candies based on given rules | Java 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
import java . util . * ; class GFG { static boolean check ( int K , int n , int m , ArrayList < Integer > arr , int good_share ) { int candies = n , taken = 0 ; while ( candies > 0 ) { taken += Math . min ( K , candies ) ; candies -= Math . min ( K , candies ) ; for ( int j = 0 ; j < m ; j ++ ) { int consume = ( arr . get ( j ) * candies ) / 100 ; candies -= consume ; } } return ( taken >= good_share ) ; } static void minimumK ( ArrayList < Integer > arr , int N , int M ) { int good_share = ( int ) Math . 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 ; } } System . out . print ( hi ) ; } public static void main ( String [ ] args ) { int N = 13 , M = 1 ; ArrayList < Integer > arr = new ArrayList < Integer > ( ) ; arr . add ( 50 ) ; minimumK ( arr , N , M ) ; } }