Given two integers A and B, representing the count of objects of two different types, and another integer N which represents the number of shelves, the task is to place all objects in the given N shelves abiding by the following rules:
- Any shelf cannot contain both Type-A and Type-B objects at the same time.
- No shelf can contain more than K objects of Type-A or L objects of type B.
If it is possible to place all the items in N shelves, print “YES”. Otherwise, print “NO”.
Input: A = 3, B = 3, N = 3, K = 4, M = 2
3 Type-A items can be placed on 1 shelf, as maximum limit is 4.
3 Type-B items can be placed on 2 shelves, as maximum limit is 2.
Since the required number of shelves does not exceed N, so allocation is possible.
Input: A = 6, B = 7, N = 3, K = 4, L = 5
6 Type-A items require 2 shelves, as maximum limit is 4.
7 Type-B items require 2 shelves, as maximum limit is 5.
Since the required number of shelves exceeds N, so allocation is not possible.
To solve the problem, we need to count the minimum number of shelves required to place all objects and check if it exceeds N or not. Follow the steps below:
Count the minimum number of items required to place Type-A items, say needa. Since, K Type-A items can be placed at most in a single shelf, following two conditions arise:
- If A is divisible by K, all Type-A items can be placed in A / K shelves.
- Otherwise, A % K items needs to be placed in 1 shelf and the rest in A / K shelves.Hence A/ K + 1 shelves are required for this case.
- Similarly, calculate the minimum number of shelves required to place Type-B items, say needb.
- If needa + needb exceeds N, allocation is not possible. Otherwise, it is possible.
Below is the implementation of the above approach.
Time complexity: O(1)
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.