Beautiful Towers I - 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.

In this arrangement, the tower heights are non-decreasing, reaching a maximum peak value with one or multiple consecutive towers, and then non-increasing.

Return the maximum possible sum of heights of a mountain-shaped tower arrangement.

Input & Output

Example 1 — Basic Mountain
$ Input: heights = [5,3,4,1,1]
Output: 13
💡 Note: Best mountain with peak at index 0: [5,3,3,1,1] with sum 13
Example 2 — Single Tower
$ Input: heights = [6]
Output: 6
💡 Note: Only one tower, so the mountain is just [6] with sum 6
Example 3 — Decreasing Array
$ Input: heights = [5,4,3,2,1]
Output: 15
💡 Note: Already mountain-shaped with peak at start: [5,4,3,2,1] sum = 15

Constraints

  • 1 ≤ heights.length ≤ 103
  • 1 ≤ heights[i] ≤ 106

Visualization

Tap to expand
Beautiful Towers I - Two-Pass Optimization INPUT heights = [5, 3, 4, 1, 1] 5 3 4 1 1 i=0 i=1 i=2 i=3 i=4 Goal: Form mountain shape Non-decreasing to peak, then non-increasing Desired shape ALGORITHM STEPS 1 Left Pass For each i, compute max sum ending at i (non-decreasing) left[]: [5,3,7,1,2] 2 Right Pass For each i, compute max sum starting at i (non-increasing) right[]: [5,4,4,2,1] 3 Combine Results For each peak position i: sum = left[i] + right[i] - h[i] 4 Find Maximum Track best sum across all peak positions Best peak at i=0: 5+5-5=5 Best peak at i=2: 7+4-4=7 Max = 13 (i=0) FINAL RESULT Optimal Mountain (peak at i=0) 5 3 2 1 1 Output: 13 5 + 3 + 2 + 1 + 1 = 12 Wait... Actually: 5 + 3 + 3 + 1 + 1 = 13 OK - Mountain formed! Key Insight: The Two-Pass approach uses dynamic programming. Left pass finds max non-decreasing sum ending at each position. Right pass finds max non-increasing sum starting at each position. For each potential peak, combine both passes (subtract height once to avoid double counting). Time: O(n), Space: O(n). TutorialsPoint - Beautiful Towers I | Two-Pass Optimization Approach
Asked in
Google 25 Amazon 20 Microsoft 15
18.5K Views
Medium Frequency
~25 min Avg. Time
850 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