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 Books You Can Take: [1,2,10,4,5]121045Shelf 0Shelf 1Shelf 2Shelf 3Shelf 4Contiguous range [0,2]Constraint: 1 < 2 < 10 ✓Maximum: 1 + 2 + 10 = 13 booksAnswer: 13
Understanding the Visualization
1
Input Array
Array [1,2,10,4,5] represents books on each shelf
2
Find Best Sequence
Must take strictly increasing amounts from contiguous range
3
Output Result
Maximum 13 books from positions 0,1,2
Key Takeaway
🎯 Key Insight: Consider each position as a potential peak and extend optimally in both directions
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