Imagine you're in a grand library where books are arranged on shelves in a special way. You have an array books where books[i] represents the number of books on the i-th shelf.
Here's the challenge: you can select any contiguous section of shelves from position l to r, but there's a strict rule - for consecutive shelves in your selection, you must take strictly fewer books from each shelf than the next one. This creates an ascending pattern in the number of books you take.
Goal: Find the maximum total number of books you can collect while following this ascending constraint.
Example: If you have [8,5,2,7,9] and choose shelves 2-4 (values [2,7,9]), you could take [1,2,3] books respectively, totaling 6 books.
Input & Output
Visualization
Time & Space Complexity
Each element is pushed and popped from stack at most once
Space for the monotonic stack and dp array
Constraints
- 1 โค books.length โค 105
- 0 โค books[i] โค 105
- The selected range must be contiguous
- Books taken must form a strictly increasing sequence