Distribute R,B beans such that each packet has at least 1 R and 1 B bean with absolute difference at most D
Last Updated :
04 Aug, 2021
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.
Examples
Input: R = 1, B = 1, D = 0
Output: Yes
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
Output: No
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:
C++
#include <bits/stdc++.h>
using namespace std;
void checkDistribution( int R, int B, int D)
{
if (max(R, B) <= min(R, B) * (D + 1)) {
cout << "Yes" ;
}
else {
cout << "No" ;
}
}
int main()
{
int R = 1, B = 1, D = 0;
checkDistribution(R, B, D);
return 0;
}
|
Java
import java.io.*;
class GFG
{
static void checkDistribution( int R, int B, int D)
{
if (Math.max(R, B) <= Math.min(R, B) * (D + 1 )) {
System.out.println( "Yes" );
}
else {
System.out.println( "No" );
}
}
public static void main(String[] args)
{
int R = 1 , B = 1 , D = 0 ;
checkDistribution(R, B, D);
}
}
|
Python3
def checkDistribution(R, B, D):
if ( max (R, B) < = min (R, B) * (D + 1 )):
print ( "Yes" )
else :
print ( "No" )
R = 1
B = 1
D = 0
checkDistribution(R, B, D)
|
C#
using System;
class GFG{
static void checkDistribution( int R, int B, int D)
{
if (Math.Max(R, B) <= Math.Min(R, B) * (D + 1)) {
Console.WriteLine( "Yes" );
}
else {
Console.WriteLine( "No" );
}
}
static public void Main()
{
int R = 1, B = 1, D = 0;
checkDistribution(R, B, D);
}
}
|
Javascript
<script>
function checkDistribution(R, B, D)
{
if (Math.max(R, B) <= Math.min(R, B) * (D + 1)) {
document.write( "Yes" );
}
else {
document.write( "No" );
}
}
let R = 1, B = 1, D = 0;
checkDistribution(R, B, D);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...