Beautiful Towers II — LeetCode 2866 Python Solution
MediumStackArrayMonotonic Stack
- Problem
- #2866
- Pattern
- Stack
- Reading time
- 6 min
- Source
- leetcode.com
The problem
You are given a 0-indexed array maxHeights of n integers. You are tasked with building n towers in the coordinate line.
Example
- Input
- maxHeights = [5,3,4,1,1]
- Output
- 13
- Explanation
- One beautiful configuration with a maximum sum is heights = [5,3,3,1,1]. This configuration is beautiful since:
Python solution
Python
class Solution:
def maximumSumOfHeights(self, maxHeights: List[int]) -> int:
n = len(maxHeights)
stk = []
left = [-1] * n
for i, x in enumerate(maxHeights):
while stk and maxHeights[stk[-1]] > x:
stk.pop()
if stk:
left[i] = stk[-1]
stk.append(i)
stk = []
right = [n] * n
for i in range(n - 1, -1, -1):
x = maxHeights[i]
while stk and maxHeights[stk[-1]] >= x:
stk.pop()
if stk:
right[i] = stk[-1]
stk.append(i)
f = [0] * n
for i, x in enumerate(maxHeights):
if i and x >= maxHeights[i - 1]:
f[i] = f[i - 1] + x
else:
j = left[i]
f[i] = x * (i - j) + (f[j] if j != -1 else 0)
g = [0] * n
for i in range(n - 1, -1, -1):
if i < n - 1 and maxHeights[i] >= maxHeights[i + 1]:
g[i] = g[i + 1] + maxHeights[i]
else:
j = right[i]
g[i] = maxHeights[i] * (j - i) + (g[j] if j != n else 0)
return max(a + b - c for a, b, c in zip(f, g, maxHeights))Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2866. Beautiful Towers II 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 2866. Beautiful Towers II?
- LeetCode 2866. Beautiful Towers II is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2866. Beautiful Towers II?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 2866. Beautiful Towers II?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2866. Beautiful Towers II cover?
- LeetCode 2866. Beautiful Towers II is tagged Stack, Array and Monotonic Stack on LeetCode.