Count maximum number of consumable candies | C ++ implememtation of the above approach ; Function to find the count of maximum consumable candies ; Store the count of total candies ; Stores the count of maximum consumable candies ; Checks if it is safe to counsume all candies ; Traverse the array arr [ ] ; If A [ i ] + M is greater than B [ i ] ; Mark all_safe as false ; Update ans ; Update ans ; Increment total by A [ i ] ; If all_safe is true ; Otherwise , ; Driver Code ; Function call to find maximum consumable candies
#include <bits/stdc++.h> NEW_LINE using namespace std ; int maximumCandy ( int candies [ ] , int safety [ ] , int N , int M ) { int total = 0 ; int ans = INT_MAX ; bool all_safe = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( candies [ i ] + M > safety [ i ] ) { all_safe = false ; ans = min ( ans , safety [ i ] ) ; } else { ans = min ( ans , candies [ i ] + M ) ; } total += candies [ i ] ; } if ( all_safe ) return total ; else return ans ; } int main ( ) { int A [ ] = { 2 , 4 , 1 , 9 , 6 } ; int B [ ] = { 8 , 7 , 3 , 12 , 7 } ; int M = 0 ; int N = sizeof ( A ) / sizeof ( A [ 0 ] ) ; cout << maximumCandy ( A , B , N , M ) ; return 0 ; }