Problem Description
Given an array of tower heights, you are allowed to remove (i.e. reduce) some bricks so that the final arrangement forms a mountain shape. This means that there is a peak (which can extend over consecutive towers) where the heights are non-decreasing from the left up to the peak and non-increasing from the peak to the right. Each tower’s new height must be no greater than its original height. Return the maximum possible sum of the tower heights in such an arrangement.
Key Insights
- The final arrangement has a peak index j such that:
- For indices i in [0, j], the heights are determined by going backwards from j: h'[i] = min(heights[i], h'[i+1]), ensuring non-decreasing order when read from left to peak.
- For indices i in [j, n-1], the heights are determined by going forwards from j: h'[i] = min(heights[i], h'[i-1]), ensuring non-increasing order from the peak.
- The transformation is done by “removing” (reducing) bricks but never adding, so every tower’s new height is at most its original height.
- By considering each index as a potential peak and computing the best possible left and right arrangements, we can compute a candidate total sum and pick the maximum.
Space and Time Complexity
Time Complexity: O(n^2) in the worst case since for each candidate peak, we potentially traverse left and right. Space Complexity: O(1) auxiliary space (ignoring input storage).
Solution
The solution iterates over all indices treating each as the peak of the mountain. For a fixed candidate peak index j:
- Compute the maximum possible sum on the left side (from index 0 to j) by traversing backwards. Start with the peak’s height, and for each index i going from j-1 to 0, update the current allowed height as the minimum of heights[i] and the height from i+1.
- Compute the maximum possible sum on the right side (from index j to n-1) by traversing forwards. Start with the peak’s height, and for each index i going from j+1 to n-1, update the current allowed height as the minimum of heights[i] and the height from i-1.
- Since the peak is counted in both left and right sums, subtract the peak’s height once.
- Keep track of the maximum mountain sum computed over all candidate peaks.
The key idea is working backwards (and forwards) from the peak, which naturally satisfies the non-decreasing (or non-increasing) property of the mountain shape while ensuring that we never exceed the original tower heights.