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

            


        
相关推荐
weixin_458872615 小时前
东华复试OJ二刷复盘2
算法
Charlie_lll5 小时前
力扣解题-637. 二叉树的层平均值
算法·leetcode
爱淋雨的男人5 小时前
自动驾驶感知相关算法
人工智能·算法·自动驾驶
wen__xvn6 小时前
模拟题刷题3
java·数据结构·算法
滴滴答滴答答6 小时前
机考刷题之 6 LeetCode 169 多数元素
算法·leetcode·职场和发展
Neteen6 小时前
【数据结构-思维导图】第二章:线性表
数据结构·c++·算法
礼拜天没时间.7 小时前
力扣热题100实战 | 第25期:K个一组翻转链表——从两两交换到K路翻转的进阶之路
java·算法·leetcode·链表·递归·链表反转·k个一组翻转链表
Swift社区7 小时前
LeetCode 400 第 N 位数字
算法·leetcode·职场和发展
再难也得平7 小时前
力扣239. 滑动窗口最大值(Java解法)
算法·leetcode·职场和发展
摩尔曼斯克的海7 小时前
力扣面试题--双指针类
python·算法·leetcode