根据题意可以知道,假设数组的长度为n,对于山状数组heights定义如下:
题目给出了山状数组中每个元素的上限,即heights[i]<=maxheights[i],题目要求返回的山状数组左右元素之和的最大值。根据以上分析可知:
class Solution:
def maximumSumOfHeights(self, maxHeights: List[int]) -> int:
n = len(maxHeights)
res = 0
for i in range(n):
pre, psum = maxHeights[i], maxHeights[i]
for j in range(i - 1, -1, -1):
pre = min(pre, maxHeights[j])
psum += pre
suf = maxHeights[i]
for j in range(i + 1, n):
suf = min(suf, maxHeights[j])
psum += suf
res = max(res, psum)
return res