打卡记录
美丽塔 II(前缀和 + 单调栈)
链接
class Solution:def maximumSumOfHeights(self, maxHeights: List[int]) -> int:n = len(maxHeights)stack = collections.deque()pre, suf = [0] * n, [0] * nfor i in range(n):while stack and maxHeights[stack[-1]] > maxHeights[i]:stack.pop()if not stack:pre[i] = (i + 1) * maxHeights[i]else:pre[i] = pre[stack[-1]] + (i - stack[-1]) * maxHeights[i]stack.append(i)ans = 0stack.clear()for i in range(n - 1, -1, -1):while stack and maxHeights[stack[-1]] > maxHeights[i]:stack.pop()if not stack:suf[i] = (n - i) * maxHeights[i]else:suf[i] = suf[stack[-1]] + (stack[-1] - i) * maxHeights[i]stack.append(i)ans = max(ans, suf[i] + pre[i] - maxHeights[i])return ans