Maximum Number of Books You Can Take Problem
Description
LeetCode Problem 2355.
You are given a 0-indexed integer array books of length n where books[i] denotes the number of books on the i^th 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.
Example 1:
Input: books = [8,5,2,7,9]
Output: 19
Explanation:
- Take 1 book from shelf 1.
- Take 2 books from shelf 2.
- Take 7 books from shelf 3.
- Take 9 books from shelf 4.
You have taken 19 books, so return 19.
It can be proven that 19 is the maximum number of books you can take.
Example 2:
Input: books = [7,0,3,4,5]
Output: 12
Explanation:
- Take 3 books from shelf 2.
- Take 4 books from shelf 3.
- Take 5 books from shelf 4.
You have taken 12 books so return 12.
It can be proven that 12 is the maximum number of books you can take.
Example 3:
Input: books = [8,2,3,7,3,4,0,1,4,3]
Output: 13
Explanation:
- Take 1 book from shelf 0.
- Take 2 books from shelf 1.
- Take 3 books from shelf 2.
- Take 7 books from shelf 3.
You have taken 13 books so return 13.
It can be proven that 13 is the maximum number of books you can take.
Constraints:
1 <= books.length <= 10^50 <= books[i] <= 10^5
Solution
Approach: Monotonic Stack + DP
Let dp[i] be the most books we can take from a segment of shelves that ends at shelf i, taking books[i] there. The takes must strictly increase to the right, so going left from i we take books[i], books[i] - 1, ... as long as the shelf has enough books and the amount stays positive.
Define nums[i] = books[i] - i. The decreasing pattern from i to the left stops at the nearest j < i with nums[j] < nums[i] (shelf j has too few books), or at j = -1 if there is none. A monotonic stack finds all these j in one pass.
Between j + 1 and i we take an arithmetic sequence with step 1 of length cnt = min(books[i], i - j), ending at books[i] and starting at u = books[i] - cnt + 1. Its sum is (u + books[i]) * cnt / 2. Beyond that we may continue the best plan that ends at j, so dp[i] = sum + (dp[j] if j != -1 else 0). The answer is the maximum of dp.
Complexity: O(n) time and O(n) extra space. Sums can exceed 32 bits, so use 64-bit integers.
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