python
class Solution:
def maxSumTrionic(self, nums: List[int]) -> int:
n = len(nums)
# ans 记录全局最大值(初始为负无穷),i 是遍历数组的指针。
ans = -inf
i = 0
while i < n:
# 第一段(严格递增)
# start 标记第一段的起点
# i 向右移动,直到不满足严格递增条件(nums[i-1] < nums[i])
start = i
i += 1
while i < n and nums[i-1] < nums[i]:
i += 1
if i == start +1:
# 第一段至少需要2个元素,否则跳过当前起点,i 继续向前。
continue
# 第二段(严格递减)
peak = i-1
res = nums[peak-1] + nums[peak] # 第一段的最后两个数必选
while i < n and nums[i-1] > nums[i]:
res += nums[i]
i += 1
if i == peak +1 or i == n or nums[i-1] == nums[i]:
# 第二段至少要有两个数,第三段至少要有两个数 ,不能有相等元素
continue
# 第三段
bottom = i-1
res += nums[i]# 第三段的前两个数必选
# 从第三段的第三个数往右,计算最大元素和
max_s = s = 0
i += 1
while i < n and nums[i-1] < nums[i]:
# max_s从第三个数开始累加
s += nums[i]
max_s = max(max_s,s)
i += 1
res += max_s
max_s = s = 0
# 从第一段的倒数第三个数往左,计算最大元素和
for j in range(peak-2,start-1,-1):
s += nums[j]
max_s = max(max_s,s)
res += max_s
ans = max(ans,res)
i = bottom
return ans