Skip to content

Commit b4a8743

Browse files
authored
Create beautiful-towers-ii.cpp
1 parent 7477d6e commit b4a8743

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed

C++/beautiful-towers-ii.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
// Time: O(n)
2+
// Space: O(n)
3+
4+
// mono stack
5+
class Solution {
6+
public:
7+
long long maximumSumOfHeights(vector<int>& maxHeights) {
8+
vector<int64_t> left(size(maxHeights));
9+
vector<int64_t> stk = {-1};
10+
for (int64_t i = 0, curr = 0; i < size(maxHeights); ++i) {
11+
while (stk.back() != stk[0] && maxHeights[stk.back()] >= maxHeights[i]) {
12+
const int j = stk.back(); stk.pop_back();
13+
curr -= (j - stk.back()) * maxHeights[j];
14+
}
15+
curr += (i - stk.back()) * maxHeights[i];
16+
stk.emplace_back(i);
17+
left[i] = curr;
18+
}
19+
int64_t result = 0, right = 0;
20+
stk = {static_cast<int64_t>(size(maxHeights))};
21+
for (int64_t i = size(maxHeights) - 1, curr = 0; i >= 0; --i) {
22+
while (stk.back() != stk[0] && maxHeights[stk.back()] >= maxHeights[i]) {
23+
const int j = stk.back(); stk.pop_back();
24+
curr -= (stk.back() - j) * maxHeights[j];
25+
}
26+
curr += (stk.back() - i) * maxHeights[i];
27+
stk.emplace_back(i);
28+
right = curr;
29+
result = max(result, left[i] + right - maxHeights[i]);
30+
}
31+
return result;
32+
}
33+
};

0 commit comments

Comments
 (0)