Maximum number of mangoes that can be bought | C ++ program for the above approach ; Function to check if mid number of mangoes can be bought ; Store the coins ; If watermelons needed are greater than given watermelons ; Store remaining watermelons if vl watermelons are used to buy mangoes ; Store the value of coins if these watermelon get sold ; Increment coins by ex ; Number of mangoes that can be buyed if only x coins needed for one mango ; If the condition is satisfied , return true ; Otherwise return false ; Function to find the maximum number of mangoes that can be bought by selling watermelons ; Initialize the boundary values ; Store the required result ; Binary Search ; Store the mid value ; Check if it is possible to buy mid number of mangoes ; Otherwise , update r to mid - 1 ; Return the result ; Driver Code ; Given Input ; Function Call
#include <bits/stdc++.h> NEW_LINE using namespace std ; bool check ( int n , int m , int x , int y , int vl ) { int temp = m ; if ( vl > n ) return false ; int ex = n - vl ; ex *= y ; temp += ex ; int cr = temp / x ; if ( cr >= vl ) return true ; return false ; } int maximizeMangoes ( int n , int m , int x , int y ) { int l = 0 , r = n ; int ans = 0 ; while ( l <= r ) { int mid = l + ( r - l ) / 2 ; if ( check ( n , m , x , y , mid ) ) { ans = mid ; l = mid + 1 ; } else r = mid - 1 ; } return ans ; } int main ( ) { int W = 4 , C = 8 , x = 4 , y = 4 ; cout << maximizeMangoes ( W , C , x , y ) ; return 0 ; }