Distribute the white and black objects into maximum groups under certain constraints
Last Updated :
12 Jul, 2021
Given W white objects and B black objects and a number D, the task is to find if it is possible to distribute the white and black objects into the maximum number of groups such that each group contains at least one of each type of object and the difference between the number of objects of different types in each group does not exceed D.
Examples:
Input: W=2, B=5, D=2
Output:
YES
Explanation:
The distribution can be as follows: {W, B, B, B} and {W, B, B}.
Each group contains at least one W and at least one B, and the difference in each group does not exceed D.
Input: W=2, B=7, D=2
Output:
NO
Approach: The maximum number of groups possible is min(W, B). Let us consider, W<B, then, there can at most W groups, and in each group there is only one W. The maximum number of B in each group will be D+1. Thus, the maximum value of B should be less than W*(D+1). This is the only necessary condition. Follow the steps below to solve the problem:
- If W is greater than B, swap W and B. (Swapping does not alter the answer)
- Check if B is greater than W*(D+1), print NO.
- Otherwise, print YES.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void isPossible( int W, int B, int D)
{
if (W > B)
swap(W, B);
if (B > W * (D + 1))
cout << "NO" << endl;
else
cout << "YES" << endl;
}
int main()
{
int W = 2;
int B = 5;
int D = 2;
isPossible(W, B, D);
return 0;
}
|
Java
import java.io.*;
class GFG
{
public static void isPossible( int W, int B, int D)
{
if (W > B) {
int temp = W;
W = B;
B = temp;
}
if (B > W * (D + 1 ))
System.out.println( "NO" );
else
System.out.println( "YES" );
}
public static void main(String[] args)
{
int W = 2 ;
int B = 5 ;
int D = 2 ;
isPossible(W, B, D);
}
}
|
Python3
def isPossible(W, B, D):
if (W > B):
temp = W
W = B
B = temp
if (B > W * (D + 1 )):
print ( "NO" )
else :
print ( "YES" )
if __name__ = = '__main__' :
W = 2
B = 5
D = 2
isPossible(W, B, D)
|
C#
using System;
class GFG {
static void isPossible( int W, int B, int D)
{
if (W > B) {
int temp = W;
W = B;
B = temp;
}
if (B > W * (D + 1))
Console.WriteLine( "NO" );
else
Console.WriteLine( "YES" );
}
public static void Main()
{
int W = 2;
int B = 5;
int D = 2;
isPossible(W, B, D);
}
}
|
Javascript
<script>
function isPossible(W, B, D)
{
if (W > B)
{
let temp = W;
W = B;
B = temp;
}
if (B > W * (D + 1))
document.write( "NO" );
else
document.write( "YES" );
}
let W = 2;
let B = 5;
let D = 2;
isPossible(W, B, D);
</script>
|
Time Complexity: O(1)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...