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
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
โ Linear Growth
Space Complexity
O(n)
Stack space and DP arrays for left and right sums
โก 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
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code