Beautiful Towers I — LeetCode 2865 Python Solution
MediumStackArrayMonotonic Stack
- Problem
- #2865
- Pattern
- Stack
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given an array heights of n integers representing the number of bricks in n consecutive towers. Your task is to remove some bricks to form a mountain-shaped tower arrangement.
Python solution
Python
class Solution:
def maximumSumOfHeights(self, maxHeights: List[int]) -> int:
ans, n = 0, len(maxHeights)
for i, x in enumerate(maxHeights):
y = t = x
for j in range(i - 1, -1, -1):
y = min(y, maxHeights[j])
t += y
y = x
for j in range(i + 1, n):
y = min(y, maxHeights[j])
t += y
ans = max(ans, t)
return ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n^2) |
| Space | O(1) auxiliary |
Pattern: Stack
When the most recent unresolved thing is the one that matters, use a stack. LeetCode 2865. Beautiful Towers I 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 2865. Beautiful Towers I?
- LeetCode 2865. Beautiful Towers I is rated Medium on LeetCode.
- What is the time complexity of LeetCode 2865. Beautiful Towers I?
- The Python solution on this page runs in O(n^2).
- What is the space complexity of LeetCode 2865. Beautiful Towers I?
- The Python solution on this page uses O(1) auxiliary space.
- What topics does LeetCode 2865. Beautiful Towers I cover?
- LeetCode 2865. Beautiful Towers I is tagged Stack, Array and Monotonic Stack on LeetCode.