VOOZH about

URL: https://www.geeksforgeeks.org/dsa/fitting-shelves-problem/

⇱ Fitting Shelves Problem - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Fitting Shelves Problem

Last Updated : 11 Jun, 2022

Given length of wall w and shelves of two lengths m and n, find the number of each type of shelf to be used and the remaining empty space in the optimal solution so that the empty space is minimum. The larger of the two shelves is cheaper so it is preferred. However cost is secondary and first priority is to minimize empty space on wall.

Examples: 

Input : w = 24 m = 3 n = 5
Output : 3 3 0
We use three units of both shelves
and 0 space is left.
3 * 3 + 3 * 5 = 24
So empty space = 24 - 24 = 0
Another solution could have been 8 0 0
but since the larger shelf of length 5
is cheaper the former will be the answer.

Input : w = 29 m = 3 n = 9 
Output : 0 3 2
0 * 3 + 3 * 9 = 27
29 - 27 = 2

Input : w = 24 m = 4 n = 7 
Output : 6 0 0
6 * 4 + 0 * 7 = 24
24 - 24 = 0

A simple and efficient approach will be to try all possible combinations of shelves that fit within the length of the wall. 
To implement this approach along with the constraint that larger shelf costs less than the smaller one, starting from 0, we increase no of larger type shelves till they can be fit. For each case we calculate the empty space and finally store that value which minimizes the empty space. if empty space is same in two cases we prefer the one with more no of larger shelves. 

Below is its implementation. 


Output
0 3 2
6 7 0

Time Complexity: O(w/max(n,m))

Space Complexity: O(1)

References: Sumologic Internship question
 

Comment
Article Tags:
Article Tags: