Skip to main content

Maximum Number of Books You Can Take - Solution & Explanation

HardPremiumFree on FleetCodeArrayDynamic ProgrammingStackMonotonic Stack7 min readAsked at: Amazon
Practice this problem

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. For each index i in the range l <= i < r, you must take strictly fewer books from shelf i than shelf i + 1.

Return the maximum number of books you can take from the bookshelf.

 

Example 1:

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.

Example 2:

Input: books = [7,0,3,4,5]
Output: 12
Explanation:
- Take 3 books from shelf 2.
- Take 4 books from shelf 3.
- Take 5 books from shelf 4.
You have taken 12 books so return 12.
It can be proven that 12 is the maximum number of books you can take.

Example 3:

Input: books = [8,2,3,7,3,4,0,1,4,3]
Output: 13
Explanation:
- Take 1 book from shelf 0.
- Take 2 books from shelf 1.
- Take 3 books from shelf 2.
- Take 7 books from shelf 3.
You have taken 13 books so return 13.
It can be proven that 13 is the maximum number of books you can take.

 

Constraints:

  • 1 <= books.length <= 105
  • 0 <= books[i] <= 105

Approach Overview

Problem Overview: You are given an array where books[i] represents the number of books on shelf i. You can pick a contiguous segment ending at i, but the number of books you take must strictly decrease by at least 1 as you move left. The goal is to maximize the total books taken.

Approach 1: Brute Force Decreasing Simulation (O(n²) time, O(1) space)

For each index i, treat it as the rightmost shelf of your selection. Move left while enforcing the decreasing rule: if you take x books from shelf i, the next shelf can contribute at most x-1, then x-2, and so on. At each step clamp the value to books[j] and stop when the allowed value becomes zero. Sum the values to compute the best segment ending at i. This direct simulation checks every possible ending position but may scan many shelves repeatedly.

Approach 2: Monotonic Stack + Dynamic Programming (O(n) time, O(n) space)

The optimal solution processes shelves from left to right and uses a monotonic stack to find how far the decreasing sequence can extend. The key observation: if you take books[i] from shelf i, the valid sequence to the left becomes books[i], books[i]-1, books[i]-2.... The smallest index you can extend to depends on when this decreasing pattern violates the actual shelf counts.

Maintain a stack of indices where the value books[i] - i is increasing. This transformation normalizes the decreasing constraint so you can quickly find the previous boundary where the pattern breaks. When processing a new shelf, pop stack elements that violate this condition. The remaining top gives the left boundary of the current valid segment.

Use dp[i] to store the maximum books you can collect for a segment ending at i. Once the boundary is known, compute the contribution of the segment using an arithmetic progression sum: the sequence decreases by 1 per step but cannot exceed the shelf's actual count. Add the previous dp value if the segment connects to an earlier valid block. This avoids recomputing sums and keeps the algorithm linear.

This technique combines Array traversal, Monotonic Stack boundary detection, and Dynamic Programming accumulation. Each index enters and leaves the stack at most once, giving true O(n) complexity.

Recommended for interviews: Interviewers expect the monotonic stack + DP solution. The brute force approach shows you understand the decreasing constraint and segment simulation, but the optimized approach demonstrates pattern recognition, stack-based boundary computation, and efficient arithmetic progression calculations.

Solution

We directly compare each row and column of the matrix grid. If they are equal, then it is a pair of equal row-column pairs, and we increment the answer by one.

The time complexity is O(n^3), where n is the number of rows or columns in the matrix grid. The space complexity is O(1).

Code

Python

Java

C++

Go

Try this approach in the editor →

Detailed Complexity Analysis

ApproachTimeSpaceWhen to Use
Brute Force Decreasing SimulationO(n²)O(1)Good for understanding the decreasing constraint and validating logic during interviews
Monotonic Stack + Dynamic ProgrammingO(n)O(n)Optimal approach for large inputs and expected solution in technical interviews

Video Solution

2355. Maximum Number of Books You Can Take (Leetcode Hard) • Angshuman Bhowmik • 4,410 views views

Watch 5 more video solutions →

Frequently Asked Questions

Is Maximum Number of Books You Can Take easy or hard?
LeetCode classifies this problem as Hard because it combines multiple concepts: monotonic stack boundaries, arithmetic sequence sums, and dynamic programming. Recognizing the books[i] - i transformation and maintaining the stack efficiently is the main challenge.
Maximum Number of Books You Can Take Python/Java solution
Most implementations use a monotonic stack and DP array. Python, Java, C++, and Go versions follow the same structure: iterate through shelves, maintain the stack condition, compute the valid segment length, and calculate the arithmetic progression sum for the decreasing sequence.
How to solve Maximum Number of Books You Can Take in O(n)?
Traverse the array while maintaining a monotonic stack of indices based on the transformed value books[i] - i. The stack helps find the farthest valid starting shelf for the decreasing sequence. Use dynamic programming to accumulate the sum of the arithmetic sequence for each valid segment ending at index i.
What is the best approach for Maximum Number of Books You Can Take?
The best approach uses a monotonic stack combined with dynamic programming. The stack identifies the nearest left boundary where the decreasing pattern breaks, while DP stores the maximum books for segments ending at each index. This reduces the problem to O(n) time and O(n) space.
Is Maximum Number of Books You Can Take asked at Google/Amazon/Meta?
Problems involving monotonic stacks and dynamic programming patterns appear frequently in interviews at companies like Google, Amazon, and Meta. Variants of range constraints, decreasing sequences, and stack-based boundary detection are common in senior-level algorithm rounds.
What data structure is used in Maximum Number of Books You Can Take?
The core data structure is a monotonic stack that maintains candidate shelf indices while preserving a specific ordering condition. Dynamic programming is used alongside it to accumulate maximum sums for valid segments. The input itself is processed as an array.
What is the time complexity of Maximum Number of Books You Can Take?
The optimal solution runs in O(n) time because each index is pushed and popped from the monotonic stack at most once. Dynamic programming stores partial results so segment sums are not recomputed. Space complexity is O(n) for the stack and DP array.

Ready to solve this problem?

Practice Maximum Number of Books You Can Take with our built-in code editor and test cases.

Practice on FleetCode