Beautiful Towers II - Problem

You are given a 0-indexed array maxHeights of n integers.

You are tasked with building n towers in the coordinate line. The ith tower is built at coordinate i and has a height of heights[i].

A configuration of towers is beautiful if the following conditions hold:

  • 1 <= heights[i] <= maxHeights[i]
  • heights is a mountain array

Array heights is a mountain if there exists an index i such that:

  • For all 0 < j <= i, heights[j - 1] <= heights[j]
  • For all i <= k < n - 1, heights[k + 1] <= heights[k]

Return the maximum possible sum of heights of a beautiful configuration of towers.

Input & Output

Example 1 — Basic Mountain
$ Input: maxHeights = [5,3,4,1,1]
Output: 14
💡 Note: Beautiful mountain with peak at index 2: heights = [4,4,4,1,1]. Sum = 4+4+4+1+1 = 14. This forms a valid mountain (non-decreasing to peak, non-increasing after).
Example 2 — Single Peak
$ Input: maxHeights = [6,5,3,9,2,7]
Output: 22
💡 Note: Best mountain has peak at index 3: heights = [3,5,3,9,2,2]. The left side increases where possible, right side decreases. Sum = 3+5+3+9+2+2 = 22.
Example 3 — Uniform Heights
$ Input: maxHeights = [3,2,5,5,2,3]
Output: 19
💡 Note: Mountain with peak at index 2 or 3: heights = [3,2,5,5,2,2]. Peak at either position 2 or 3 gives optimal result. Sum = 3+2+5+5+2+2 = 19.

Constraints

  • 1 ≤ maxHeights.length ≤ 105
  • 1 ≤ maxHeights[i] ≤ 109

Visualization

Tap to expand
Beautiful Towers II - Optimal Solution INPUT maxHeights array visualization 5 3 4 1 1 i=0 i=1 i=2 i=3 i=4 maxHeights = [5, 3, 4, 1, 1] n = 5 towers Find max sum mountain heights[i] <= maxHeights[i] Mountain: increase then decrease ALGORITHM STEPS 1 Compute left[] array Max sum from left to peak i Using monotonic stack 2 Compute right[] array Max sum from right to peak i Using monotonic stack 3 Try each peak position For i in [0,n-1]: combine sum = left[i] + right[i] - h[i] 4 Track maximum sum Return best configuration Peak at i=1 (best case) left[]: [5,8,--,--,--] right[]: [--,8,6,2,1] heights: [3,3,4,1,1] Wait - peak i=2 is better: heights=[3,3,4,1,1]=12 Best: [5,3,4,1,1]=14 (i=0) FINAL RESULT Optimal Mountain Configuration 5 3 2 1 1 PEAK Decreasing from peak Maximum Sum: 14 5+3+2+1+1 or 5+3+4+1+1 [OK] Valid mountain array Key Insight: Use monotonic stack to efficiently compute prefix/suffix sums. For each position i as potential peak, left[i] stores max sum of increasing sequence ending at i, right[i] stores max sum of decreasing sequence starting at i. Answer = max(left[i] + right[i] - maxHeights[i]) for all i. Time: O(n) TutorialsPoint - Beautiful Towers II | Monotonic Stack Approach
Asked in
Google 15 Microsoft 12 Amazon 8
25.0K Views
Medium Frequency
~25 min Avg. Time
890 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