Count maximum number of consumable candies | Java 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
public class GFG { static int maximumCandy ( int [ ] candies , int [ ] safety , int N , int M ) { int total = 0 ; int ans = Integer . MAX_VALUE ; boolean all_safe = true ; for ( int i = 0 ; i < N ; i ++ ) { if ( candies [ i ] + M > safety [ i ] ) { all_safe = false ; ans = Math . min ( ans , safety [ i ] ) ; } else { ans = Math . min ( ans , candies [ i ] + M ) ; } total += candies [ i ] ; } if ( all_safe ) return total ; else return ans ; } public static void main ( String [ ] args ) { int A [ ] = { 4 , 5 , 2 , 3 } ; int B [ ] = { 8 , 13 , 6 , 4 } ; int M = 5 ; int N = A . length ; System . out . println ( maximumCandy ( A , B , N , M ) ) ; } }