Beautiful Towers II - Monotonic Increasing Stack [JS]
Description Solution: Monotonic Increasing Stack Find the maximum possible sum of heights ending and starting at each index i . left : left[i] = sum of heights from ( 0, ..., i ) such that they are descending from index i to 0 . right : right[i] = sum of heights from ( i, ..., n - 1 ) such that they are descending from index i to n - 1 . Use a monotonic increasing stack to store indices of maxHeights such that they are smaller than maxHeights[i] . left to right: We know that from index i to stack[stack.length - 1] , all heights are smaller than maxHeights[i] . Take the existing sum up to stack[stack.length - 1] ( left[stack[stack.length - 1]] ) and add the sum for the current range ( maxHeights[i] * (i - stack[stack.length - 1]) ) Then, do the same from right to left. Take each maxHeights[i] as the peak of the mountain and use the results from ...