The "Beautiful Towers II interview question" is the optimized version of the mountain-height problem. Like the first version, you must find a peak index such that the sum of heights (limited by maxHeight and forming a mountain shape) is maximized. However, the constraints are much larger (), requiring a linear solution instead of the brute force.
Companies like Salesforce and Amazon use the "Beautiful Towers II coding problem" to test a candidate's mastery of the Monotonic Stack. It requires pre-calculating the "cost" of making a mountain to the left and to the right for every single index. It evaluates advanced "Array interview pattern" skills and the ability to handle cumulative sums with stack-based boundaries.
This problem is a classic application of the Monotonic Stack and Dynamic Programming patterns.
dp_left[i] stores the max sum of a non-decreasing sequence ending at i.stack is empty, all previous towers are limited by maxHeight[i].stack has index j, then towers from j+1 to i are limited by maxHeight[i], and we add dp_left[j].dp_right[i].dp_left[i] + dp_right[i] - maxHeight[i].maxHeights = [6, 5, 3, 9, 2]
dp_left[2] (value 3):
dp_left[2] = 3 * 3 = 9.dp_left[3] (value 9):
dp_left[3] = dp_left[2] + 9 = 18.Master the "Nearest Smaller Element" pattern using a monotonic stack. It is the secret weapon for many linear-time array problems. Practice "Largest Rectangle in Histogram" and "Sum of Subarray Minimums" to build this intuition.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Count Bowl Subarrays | Medium | Solve | |
| Maximal Range That Each Element Is Maximum in It | Medium | Solve | |
| Maximum of Minimum Values in All Subarrays | Medium | Solve | |
| Beautiful Towers I | Medium | Solve | |
| Buildings With an Ocean View | Medium | Solve |