Ctrl K

Books in Rising Order

Hard
A bookcase has n shelves, and shelf i holds shelves[i] books. Choose a contiguous run of shelves l..r (0 ≤ l ≤ r < n) and take books from every shelf in it. There is one rule: from each shelf i with l ≤ i < r you must take **strictly fewer** books than from the next shelf i + 1. You cannot take more books than a shelf holds, but taking zero is allowed. Return the largest number of books you can carry away.
Example 1
shelves=[4, 1, 5, 6] → 12

Take shelves 0 through 3: 0, 1, 5 and 6 books. Shelf 0 gives 0 because only one book comes from shelf 1. The total is 12.

Example 2
shelves=[3, 3, 3] → 6

Take 1, 2 and 3 books, 6 in total.

Example 3
shelves=[0] → 0
Constraints
  • 1 ≤ n = len(shelves) ≤ 10⁵
  • 0 ≤ shelves[i] ≤ 10⁵
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsWater Between Walls HardBiggest Solid Panel Block HardFrog on the Posts HardRaising by Ranges HardLong Leaps Across a Board Hard
loading Python…
Input
shelves=[4, 1, 5, 6]
Expected
12

Run checks the first 3 tests in your browser. Submit checks all 143 tests on the server, hidden ones included.