LeetCode solutions

1196. Filling Bookcase Shelves

My accepted Python solution to LeetCode problem 1196, Filling Bookcase Shelves, running in 0ms.

  • Difficulty: Medium
  • Python
  • Runtime 0ms
  • Memory 17.7MB

Read the problem on LeetCode View on GitHub

Python

Accepted on LeetCode — runtime 0ms, memory 17.7MB, accepted 2026-01-02.

python
class Solution:
    def minHeightShelves(self, books: List[List[int]], shelfWidth: int) -> int:
        n = len(books)
        # dp[i] = minimum height to place first i books
        dp = [float('inf')] * (n + 1)
        dp[0] = 0
        
        for i in range(1, n + 1):
            # Try placing books j+1 to i on the same shelf
            width = 0
            height = 0
            for j in range(i - 1, -1, -1):
                width += books[j][0]
                if width > shelfWidth:
                    break
                height = max(height, books[j][1])
                dp[i] = min(dp[i], dp[j] + height)
        
        return dp[n]

Source