The Maximum Number of Books You Can Take coding problem gives you shelves with a given number of books. You want to choose a contiguous segment of shelves and take as many books as possible, subject to the constraint that the number of books taken from each shelf must form a strictly increasing sequence from left to right, and from each shelf you can take at most as many books as are on it.
Amazon includes this problem because it requires a non-obvious combination of monotonic stack with dynamic programming. The constraint — strictly increasing, bounded above by shelf count — means that for any right endpoint, you need to efficiently find the optimal left starting point. The monotonic stack prunes impossible left endpoints, while DP computes the maximum books for each right endpoint.
Monotonic stack + DP: For each right endpoint r (the last shelf), the books taken form the sequence books[r], books[r]-1, books[r]-2, ..., books[r]-k+1 for some k, going left from r. The sequence is constrained by each shelf's capacity: you can't take more than books[i] from shelf i.
Use a monotonic stack to find, for each r, the leftmost valid start l where books[l] >= books[r] - (r - l). For the valid segment, sum the arithmetic progression. The DP value dp[r] = sum of taken books with r as the last shelf.
Shelves: [8, 5, 2, 7, 2, 6]
For r=5 (books=6), taking sequence going left: 6, 5, 4, ... but shelf at index 4 has only 2 books, so you can take at most 2 from it. The sequence would be: take 6 from shelf 5, 5 from shelf 3 (wait, they must be contiguous).
The monotonic stack finds the valid segment boundary efficiently. DP[r] = max books for all valid starting points.
For the Array Monotonic Stack Stack Dynamic Programming interview pattern, this problem exemplifies the "stack-optimized DP" technique. When a DP transition requires finding the best left boundary satisfying a monotone condition, a monotonic stack achieves this in amortized O(1) per step. Practice this on simpler variants before attempting this problem.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Sum of Subarray Minimums | Medium | Solve | |
| Minimum Operations to Make Array Equal to Target | Hard | Solve | |
| Minimum Number of Increments on Subarrays to Form a Target Array | Hard | Solve | |
| Maximal Rectangle | Hard | Solve | |
| Trapping Rain Water | Hard | Solve |