LeetCode 1105: Filling Bookcase Shelves Solution
Master LeetCode problem 1105 (Filling Bookcase Shelves), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1105. Filling Bookcase Shelves
Problem Explanation
Explanation
To solve this problem, we can use dynamic programming to determine the minimum possible height of the total bookshelf after placing shelves in the given manner. We can define a dp array where dp[i] represents the minimum possible height for placing the first i books on shelves. At each step, we iterate through the previous books to find the optimal height that minimizes the total height of the bookcase.
- Initialize a dp array of size n+1 where n is the number of books.
- Initialize dp[0] = 0 to represent the minimum height when no books are placed.
- Iterate through books array and update dp[i] based on the optimal height up to that point.
- Return dp[n] where n is the number of books.
Time Complexity: O(n^2) where n is the number of books.
Space Complexity: O(n)
Solution Code
class Solution {
public int minHeightShelves(int[][] books, int shelfWidth) {
int n = books.length;
int[] dp = new int[n + 1];
for (int i = 1; i <= n; i++) {
int width = 0;
int maxHeight = 0;
dp[i] = Integer.MAX_VALUE;
for (int j = i; j > 0; j--) {
width += books[j - 1][0];
maxHeight = Math.max(maxHeight, books[j - 1][1]);
if (width > shelfWidth) break;
dp[i] = Math.min(dp[i], dp[j - 1] + maxHeight);
}
}
return dp[n];
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1105 (Filling Bookcase Shelves)?
This page provides optimized solutions for LeetCode problem 1105 (Filling Bookcase Shelves) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1105 (Filling Bookcase Shelves)?
The time complexity for LeetCode 1105 (Filling Bookcase Shelves) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1105 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1105 in Java, C++, or Python.