Beautiful Towers I - Problem

Imagine you're an architect tasked with creating a beautiful mountain-shaped skyline from a row of towers! ๐Ÿ—๏ธ

You are given an array heights of n integers representing the number of bricks in n consecutive towers. Your goal is to remove some bricks to create a stunning mountain-shaped arrangement where:

  • Tower heights are non-decreasing up to the peak
  • There's one or more consecutive towers at the maximum height (the peak)
  • Tower heights are non-increasing after the peak

For example, arrays like [1, 2, 3, 3, 2, 1] or [1, 4, 4, 4, 1] are beautiful mountain shapes!

Your task: Return the maximum possible sum of all tower heights after creating the perfect mountain arrangement.

Input & Output

example_1.py โ€” Python
$ Input: [5, 3, 4, 1, 1]
โ€บ Output: 13
๐Ÿ’ก Note: Choose index 2 as peak. Left side becomes [3,3,4] and right side becomes [4,1,1]. Total sum = 3+3+4+1+1 = 13
example_2.py โ€” Python
$ Input: [6, 5, 3, 9, 2, 7]
โ€บ Output: 22
๐Ÿ’ก Note: Choose index 3 as peak. Mountain becomes [3,5,3,9,2,2]. Total sum = 3+5+3+9+2+2 = 22
example_3.py โ€” Python
$ Input: [3, 2, 5, 5, 2, 3]
โ€บ Output: 18
๐Ÿ’ก Note: Choose indices 2-3 as peak plateau. Mountain becomes [3,2,5,5,2,3]. No changes needed, sum = 18

Visualization

Tap to expand
PEAKBeautiful Mountain: Sum = 13Original: [5,3,4,1,1]Mountain: [3,3,4,1,1]
Understanding the Visualization
1
Original Towers
Start with towers of different heights [5,3,4,1,1]
2
Try Peak at Index 2
Height 4 becomes our peak, adjust surrounding towers
3
Build Left Side
Create non-decreasing sequence: [3,3,4]
4
Build Right Side
Create non-increasing sequence: [4,1,1]
5
Calculate Sum
Final mountain: [3,3,4,1,1] with sum = 13
Key Takeaway
๐ŸŽฏ Key Insight: The optimal peak position maximizes the total sum while maintaining the mountain property. Use monotonic stacks to compute contributions efficiently!

Time & Space Complexity

Time Complexity
โฑ๏ธ
O(n)

Each element is pushed and popped from stack at most once

n
2n
โœ“ Linear Growth
Space Complexity
O(n)

Stack space and DP arrays for left and right sums

n
2n
โšก Linearithmic Space

Constraints

  • 1 โ‰ค heights.length โ‰ค 103
  • 1 โ‰ค heights[i] โ‰ค 109
  • Mountain must have exactly one peak region
  • You can only remove bricks, never add them
Asked in
Google 42 Amazon 38 Meta 25 Microsoft 19
38.2K Views
Medium-High Frequency
~25 min Avg. Time
1.5K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen