Leetcode #2355: Maximum Number of Books You Can Take
In this guide, we solve Leetcode #2355 Maximum Number of Books You Can Take in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
You are given a 0-indexed integer array books of length n where books[i] denotes the number of books on the ith shelf of a bookshelf. You are going to take books from a contiguous section of the bookshelf spanning from l to r where 0 <= l <= r < n.
Quick Facts
- Difficulty: Hard
- Premium: Yes
- Tags: Stack, Array, Dynamic Programming, Monotonic Stack
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
Example
Input: books = [8,5,2,7,9]
Output: 19
Explanation:
- Take 1 book from shelf 1.
- Take 2 books from shelf 2.
- Take 7 books from shelf 3.
- Take 9 books from shelf 4.
You have taken 19 books, so return 19.
It can be proven that 19 is the maximum number of books you can take.
Python Solution
class Solution:
def maximumBooks(self, books: List[int]) -> int:
nums = [v - i for i, v in enumerate(books)]
n = len(nums)
left = [-1] * n
stk = []
for i, v in enumerate(nums):
while stk and nums[stk[-1]] >= v:
stk.pop()
if stk:
left[i] = stk[-1]
stk.append(i)
ans = 0
dp = [0] * n
dp[0] = books[0]
for i, v in enumerate(books):
j = left[i]
cnt = min(v, i - j)
u = v - cnt + 1
s = (u + v) * cnt // 2
dp[i] = s + (0 if j == -1 else dp[j])
ans = max(ans, dp[i])
return ans
Complexity
The time complexity is , where is the number of rows or columns in the matrix . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.