Leetcode #2865: Beautiful Towers I
In this guide, we solve Leetcode #2865 Beautiful Towers I in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Medium
- Premium: No
- Tags: Stack, Array, Monotonic Stack
Intuition
We need the next greater or smaller element efficiently, which is exactly what a monotonic stack offers.
Each element is pushed and popped at most once, yielding a linear-time scan.
Approach
Maintain a stack that is either increasing or decreasing, depending on the query.
When the invariant is broken, pop and resolve answers for those indices.
Steps:
- Scan elements once.
- Pop while the monotonic condition is violated.
- Use stack indices to update answers.
Python Solution
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 ans
Complexity
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.