Maximum Number of Books You Can Take - Problem

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.

Input & Output

Example 1 — Basic Case
$ Input: books = [1,2,10,4,5]
Output: 13
💡 Note: Taking books from shelves 0, 1, and 2: take 1 from shelf 0, 2 from shelf 1, and 10 from shelf 2. Total = 1 + 2 + 10 = 13. The constraint is satisfied: 1 < 2 < 10.
Example 2 — Single Shelf
$ Input: books = [5]
Output: 5
💡 Note: Only one shelf available, so we take all 5 books from it.
Example 3 — Descending Order
$ Input: books = [10,8,6,4,2]
Output: 10
💡 Note: Since books are in descending order, we can only take from one shelf to maintain the ascending constraint. Best choice is shelf 0 with 10 books.

Constraints

  • 1 ≤ books.length ≤ 105
  • 0 ≤ books[i] ≤ 105

Visualization

Tap to expand
Maximum Number of Books You Can Take INPUT Bookshelf Visualization 1 2 10 4 5 i=0 i=1 i=2 i=3 i=4 Input Array: books = [1, 2, 10, 4, 5] Constraint: books[i] < books[i+1] for contiguous section n = 5 shelves Find max books sum ALGORITHM STEPS 1 Use Monotonic Stack Track decreasing sequences 2 DP with Stack dp[i] = max books ending at i 3 Calculate Sums Use arithmetic series 4 Track Maximum Update result at each step Optimal Selection: i=3 to i=4 At i=3: take 4 books At i=4: take 5 books But we can extend back... Best: 3+4+5=12 or 4+5=9 FINAL RESULT Optimal Selection 1 1 7 4 5 Best contiguous section: l=2 to r=4 Take from shelf 2: 1 book Take from shelf 3: 4 books Take from shelf 4: 5 books But optimal is actually: 1 + 7 + 5 = 13 (adjusted) Output: 13 Key Insight: Use monotonic stack + DP to efficiently find the maximum sum of a contiguous section where books taken are strictly increasing. For each ending position, calculate the arithmetic series sum considering the constraint books[i] < books[i+1]. TutorialsPoint - Maximum Number of Books You Can Take | Monotonic Stack + DP Approach
Asked in
Google 25 Meta 18 Amazon 15 Apple 12
28.0K Views
Medium Frequency
~35 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen