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

            


        
相关推荐
稚南城才子,乌衣巷风流36 分钟前
ST 表(Sparse Table)算法详解:原理、实现与应用
算法
hold?fish:palm41 分钟前
9 找到字符串中所有字母异位词
c++·算法·leetcode
Sw1zzle1 小时前
算法入门(六):贪心算法 - 基础入门(Leetcode 121/455/860/376/738)
算法·leetcode·贪心算法
青山木1 小时前
Hot 100 --- 岛屿数量
java·数据结构·算法·leetcode·深度优先·广度优先
不会就选b2 小时前
算法日常・每日刷题--<归并排序>1
数据结构·算法
危桥带雨2 小时前
排序算法(快排、归并、计数、基数排序)
数据结构·算法·排序算法
啦啦啦啦啦zzzz2 小时前
算法:回溯算法
c++·算法·leetcode
IT探索2 小时前
Linux 查找文件指令总结
linux·算法
zephyr052 小时前
数据结构-并查集
数据结构