Check if all 3 Candy bags can be emptied by removing 2 candies from any one bag and 1 from the other two repeatedly
Given 3 integers a, b and c indicating number of candies present in three bags. You need to find whether we can empty all the bags by performing a specific operation where in each operation, you can eat 2 candies from one bag and 1 candy each from the other 2 bags. It is not permittable to skip any bag i.e either 1 or 2 candies must be eaten from each bag in each operation. Return true if possible else return false.
Input: 4, 2, 2
Operation 1: you can eat 2 candies from bag1 and 1 from bag2 and bag3 each.
Candies left after operation 1
bag1 = 2, bag2 = 1, bag3 = 1
Operation 2: you can eat 2 candies from bag1 and 1 from each bag2 and bag3 each
Candies left after operation 2
bag1 = 0, bag2 = 0, bag3 = 0
Hence it is possible to empty all the bags
Input: 3, 4, 2
Naive Approach: Iterate through the variables until all three does not become 0. At every iteration reduce the maximum element by 2 and remaining variables by 1.
Time Complexity: O(N), where N is value of maximum variable of a, b and c
Efficient Approach: The given problem can be solved with the efficient approach by making the following observations:
- In each operation we’ll pick 1+2+1=4 candies, hence the sum of all the candies in bag1, bag2, and bag3 must be divisible by 4.
- Number of operations required to empty all the bags would be (sum of all candies)/4.
- We have to pick either 1 or 2 candies from a bag at any operation, hence the minimum candies present of the 3 bags must be greater than or equal to the number of operations.
Time Complexity: O(1) since no loop is used the algorithm takes up constant time to perform the operations
Space Complexity: O(1) since no extra array is used so the space taken by the algorithm is constant