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.
To maximize the sum while forming a mountain, for each possible peak, we want to keep the tallest possible towers to the left and right, but never exceeding the peak. We use monotonic stacks to efficiently compute the maximum sum for each peak.
classSolution {
publiclongmaximumSumOfHeights(int[] h) {
int n = h.length;
long[] left =newlong[n], right =newlong[n];
Deque<Integer> st =new ArrayDeque<>();
for (int i = 0; i < n; ++i) {
while (!st.isEmpty() && h[st.peek()]> h[i]) st.pop();
if (st.isEmpty()) left[i]= 1L * h[i]* (i + 1);
else left[i]= left[st.peek()]+ 1L * h[i]* (i - st.peek());
st.push(i);
}
st.clear();
for (int i = n - 1; i >= 0; --i) {
while (!st.isEmpty() && h[st.peek()]> h[i]) st.pop();
if (st.isEmpty()) right[i]= 1L * h[i]* (n - i);
else right[i]= right[st.peek()]+ 1L * h[i]* (st.peek() - i);
st.push(i);
}
long ans = 0;
for (int i = 0; i < n; ++i) ans = Math.max(ans, left[i]+ right[i]- h[i]);
return ans;
}
}
classSolution {
funmaximumSumOfHeights(h: IntArray): Long {
val n = h.size
val left = LongArray(n)
val right = LongArray(n)
val st = ArrayDeque<Int>()
for (i in0 until n) {
while (st.isNotEmpty() && h[st.last()] > h[i]) st.removeLast()
if (st.isEmpty()) left[i] = h[i].toLong() * (i + 1)
else left[i] = left[st.last()] + h[i].toLong() * (i - st.last())
st.addLast(i)
}
st.clear()
for (i in n - 1 downTo 0) {
while (st.isNotEmpty() && h[st.last()] > h[i]) st.removeLast()
if (st.isEmpty()) right[i] = h[i].toLong() * (n - i)
else right[i] = right[st.last()] + h[i].toLong() * (st.last() - i)
st.addLast(i)
}
var ans = 0Lfor (i in0 until n) ans = maxOf(ans, left[i] + right[i] - h[i])
return ans
}
}
classSolution:
defmaximumSumOfHeights(self, h: list[int]) -> int:
n = len(h)
left = [0]*n
right = [0]*n
st = []
for i in range(n):
while st and h[st[-1]] > h[i]:
st.pop()
ifnot st:
left[i] = h[i]*(i+1)
else:
left[i] = left[st[-1]] + h[i]*(i-st[-1])
st.append(i)
st.clear()
for i in range(n-1, -1, -1):
while st and h[st[-1]] > h[i]:
st.pop()
ifnot st:
right[i] = h[i]*(n-i)
else:
right[i] = right[st[-1]] + h[i]*(st[-1]-i)
st.append(i)
ans =0for i in range(n):
ans = max(ans, left[i]+right[i]-h[i])
return ans