MediumNo. 2865

Beautiful Towers I — LeetCode 2865 Python Solution

Pattern
Stack
Topics
Stack, Array, Monotonic Stack
Reading time
2 min

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

PythonSolution
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

Time
O(n2)
Space · auxiliary
O(1)

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

Related problems
No.ProblemDifficulty
2866Beautiful Towers IIMedium
0084Largest Rectangle in HistogramHard
0456132 PatternMedium
0503Next Greater Element IIMedium
0654Maximum Binary TreeMedium
0739Daily TemperaturesMedium

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(n2).

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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.