Leetcode 1105: Filling Bookcase Shelves

grid47
grid47
Exploring patterns and algorithms
Jul 19, 2024 7 min read

You are given an array of books where each book is represented by a pair of integers [thickness, height]. Additionally, you have a shelf with a fixed width. Your goal is to arrange the books on the shelves such that each shelf’s total thickness is less than or equal to the shelf width, and the height of each shelf is determined by the tallest book placed on it. The books must be placed in the same order as they appear in the input array. The objective is to minimize the total height of the bookshelf.
Problem
Approach
Steps
Complexity
Input: You are given an array `books` where each element is a pair `[thickness, height]` indicating the thickness and height of a book. You are also given an integer `shelfWidth`, which represents the width of the shelf.
Example: books = [[1, 2], [3, 5], [2, 2], [1, 3]], shelfWidth = 6
Constraints:
• 1 <= books.length <= 1000
• 1 <= thicknessi <= shelfWidth <= 1000
• 1 <= heighti <= 1000
Output: The output is a single integer representing the minimum possible height of the bookshelf after placing all the books on the shelves.
Example: Output: 8
Constraints:
• The books must be placed in the same order as they appear in the input array.
Goal: The goal is to minimize the total height of the bookshelf by optimally placing books onto the shelves.
Steps:
• Start with an empty bookshelf and iterate over the books.
• For each book, check if it can be placed on the current shelf without exceeding the shelf width. If yes, place it on the shelf.
• If the book cannot fit, start a new shelf, keeping track of the height of the tallest book on each shelf.
• At each step, keep track of the total height of the bookshelf.
Goal: The problem is to efficiently arrange the books on shelves while minimizing the total height of the bookshelf.
Steps:
• Each shelf has a maximum width limit defined by `shelfWidth`.
• The total height of a shelf is determined by the tallest book on it.
• Books must be placed in the order they are given.
Assumptions:
• All input values are within the defined constraints.
• The books must be placed on the shelf in the order given.
Input: Input: books = [[1, 2], [3, 5], [2, 2], [1, 3]], shelfWidth = 6
Explanation: In this example, the first shelf can hold books [1, 2] and [3, 5] because their combined thickness is 4, which is less than the shelfWidth of 6. The second shelf holds books [2, 2] and [1, 3] with a combined thickness of 3. The final height is 8 (2 from the first shelf, and 5 from the second shelf).

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus