Maximum Number of Books You Can Take — LeetCode 2355 Python Solution

HardLeetCode PremiumStackArrayDynamic ProgrammingMonotonic Stack
Problem
#2355
Pattern
Stack
Reading time
4 min

The 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.

Example

Input
books = [8,5,2,7,9]
Output
19
Explanation
- Take 1 book from shelf 1.

Python solution

Python
class Solution:
    def maximumBooks(self, books: List[int]) -> int:
        nums = [v - i for i, v in enumerate(books)]
        n = len(nums)
        left = [-1] * n
        stk = []
        for i, v in enumerate(nums):
            while stk and nums[stk[-1]] >= v:
                stk.pop()
            if stk:
                left[i] = stk[-1]
            stk.append(i)
        ans = 0
        dp = [0] * n
        dp[0] = books[0]
        for i, v in enumerate(books):
            j = left[i]
            cnt = min(v, i - j)
            u = v - cnt + 1
            s = (u + v) * cnt // 2
            dp[i] = s + (0 if j == -1 else dp[j])
            ans = max(ans, dp[i])
        return ans

Complexity

MeasureComplexity
TimeO(n^3), where n is the number of rows or columns in the matrix grid
SpaceO(1) auxiliary

Pattern: Stack

When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2355. Maximum Number of Books You Can Take is filed here because LeetCode tags it Stack, which is the vocabulary this hub collects.

The stack guide has the Python template for the pattern and the 194 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 2355. Maximum Number of Books You Can Take?
LeetCode 2355. Maximum Number of Books You Can Take is rated Hard on LeetCode.
What topics does LeetCode 2355. Maximum Number of Books You Can Take cover?
LeetCode 2355. Maximum Number of Books You Can Take is tagged Stack, Array, Dynamic Programming and Monotonic Stack on LeetCode.
Is LeetCode 2355. Maximum Number of Books You Can Take a premium problem?
Yes. LeetCode 2355. Maximum Number of Books You Can Take is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview