3640. 三段式数组 II

3640. 三段式数组 II

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

            


        
相关推荐
淡海水9 小时前
07-04-并发-ConcurrentBag-T-工作窃取WorkStealing算法
开发语言·算法·c#·bag·concurrent·workstealing
leobertlan10 小时前
好玩系列:训练一个神经网络模型指导小孩玩游戏2-大局观教练
算法
Tisfy10 小时前
LeetCode 3876.构造奇偶一致的数组 II:三种情况分类讨论(其实还是脑筋急转弯)
算法·leetcode·题解·脑筋急转弯
乐迪信息11 小时前
智慧港口船舶AI算法实现在线状态监测
大数据·人工智能·深度学习·算法·计算机视觉
kiracrimson12 小时前
从缓存的角度看链表与线性表的差异
数据结构·链表·缓存
木井巳13 小时前
【BFS/DFS 解决 FloodFill 算法】太平洋大西洋水流问题
java·算法·leetcode·深度优先·广度优先·宽度优先·推荐算法
心抵鹊13 小时前
归并排序之翻转对(hard)
数据结构·算法
白山编程大哥13 小时前
Java 集合算法:从排序、查找到底层原理的实战指南
java·python·算法
shehuiyuelaiyuehao13 小时前
算法34,位运算符操作,总结
算法
Navigator_Z14 小时前
LeetCode //C - 1224. Maximum Equal Frequency
c语言·算法·leetcode