Distribute R,B beans such that each packet has at least 1 R and 1 B bean with absolute difference at most D
Given two positive integers R and B representing R red and B blue beans and an integer D, the task is to check whether it is possible to distribute the beans among several (maybe, one) packets according to the following rules:
- Each packet has at least one red bean.
- Each packet has at least one blue bean.
- The number of red and blue beans in each packet should differ in no more than D (or |R-B| <= D)
Print Yes if it is possible. Otherwise, print No.
Attention reader! Don’t stop learning now. Get hold of all the important mathematical concepts for competitive programming with the Essential Maths for CP Course at a student-friendly price. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Input: R = 1, B = 1, D = 0
Explanation: Form one packet with 1 red and 1 blue bean. The absolute difference |1−1| = 0 ≤ D.
Input: R = 6, B = 1, D = 4
Approach: This problem can be solved easily by observing that the maximum of (R and B) is D + 1 times the minimum of R and B. Follow the steps given below to solve the problem:
- Find the maximum of R and B. and the minimum of R and B.
- To satisfy the given 3 constraints, the value of the max(R, B) should be at most (D + 1) times min(R, B), because (D + 1) beans can be kept in each packet, 1 bean of one type, and D beans of the other type.
- After completing the above steps, print “Yes” if the value of the max(R, B) is less than or equal to (D + 1)*min(R, B). Otherwise, print “No”.
Below is the implementation of the above approach:
Time Complexity: O(1)
Auxiliary Space: O(1)