Skip to content

Commit

Permalink
Create 2355.Maximum-Number-of-Books-You-Can-Take.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
wisdompeak authored Sep 19, 2022
1 parent 78a0da3 commit 75665c6
Showing 1 changed file with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
using LL = long long;
class Solution {
public:
long long maximumBooks(vector<int>& books)
{
int n = books.size();
vector<LL>dp(n);
stack<LL>stk;

LL ret = 0;
for (int i=0; i<n; i++)
{
while (!stk.empty() && books[stk.top()] > books[i]-(i-stk.top()))
stk.pop();

if (!stk.empty())
{
LL d = i - stk.top();
dp[i] = dp[stk.top()] + ((LL)books[i] + (LL)books[i] - d + 1) * d /2;
}
else
{
LL d = min(i + 1, books[i]);
dp[i] = ((LL)books[i] + (LL)books[i] - d + 1) * d /2;
}
stk.push(i);

ret = max(ret, dp[i]);
}

return ret;
}
};

0 comments on commit 75665c6

Please sign in to comment.