Beautiful Towers II - Problem

Imagine you're an architect tasked with designing a stunning skyline along a coordinate line. You have n positions where you must build towers, and each position i has a maximum height constraint maxHeights[i].

Your goal is to create a beautiful mountain-shaped configuration that maximizes the total height sum. A configuration is considered beautiful when:

  • Each tower's height is between 1 and maxHeights[i]
  • The heights form a mountain array - they increase up to a peak, then decrease

Mountain Array Definition: There exists a peak index i where heights are non-decreasing from left to peak (heights[j-1] ≤ heights[j] for all j ≤ i) and non-increasing from peak to right (heights[k] ≥ heights[k+1] for all k ≥ i).

Return the maximum possible sum of heights for a beautiful tower configuration.

Input & Output

basic_mountain.py — Python
$ Input: maxHeights = [5,3,4,1,1]
Output: 13
💡 Note: One optimal configuration is heights = [2,3,3,1,1] with peak at index 1 or 2. The sum is 2+3+3+1+1 = 10. Actually, the optimal is [4,3,4,1,1] = 13 with peak at index 0 or 2.
increasing_array.py — Python
$ Input: maxHeights = [6,5,3,9,2,7]
Output: 22
💡 Note: One optimal configuration is heights = [3,5,3,3,2,2] with peak at index 1. Sum = 3+5+3+3+2+2 = 18. Better: [6,5,3,3,2,2] = 21 or [3,3,3,9,2,2] = 22 with peak at index 3.
single_element.py — Python
$ Input: maxHeights = [3]
Output: 3
💡 Note: With only one tower, the optimal height is the maximum allowed height 3, giving sum = 3.

Visualization

Tap to expand
Beautiful Towers Mountain Building510151273PeakOptimal Mountain ConfigurationHeights: [5, 10, 15, 12, 7, 3] → Mountain: [5, 10, 15, 12, 7, 3] = 52
Understanding the Visualization
1
Identify Constraints
Each position has a maximum height limit that restricts our building options
2
Try Different Peaks
For each potential peak, calculate the optimal left and right slopes
3
Optimize with Stacks
Use monotonic stacks to avoid recalculating overlapping slope contributions
Key Takeaway
🎯 Key Insight: The optimal peak position creates the tallest mountain by balancing the constraints on both left and right slopes, maximizing the total area under the mountain curve.

Time & Space Complexity

Time Complexity
⏱️
O(n)

Each element is pushed and popped from stack at most once, two passes through array

n
2n
Linear Growth
Space Complexity
O(n)

Space for monotonic stacks and left/right contribution arrays

n
2n
Linearithmic Space

Constraints

  • 1 ≤ maxHeights.length ≤ 105
  • 1 ≤ maxHeights[i] ≤ 109
  • The answer is guaranteed to fit in a 64-bit integer
Asked in
Google 12 Meta 8 Amazon 6 Microsoft 4
28.4K Views
Medium Frequency
~25 min Avg. Time
680 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