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

            


        
相关推荐
Yzzz-F9 小时前
Problem - 2146D1 - Codeforces &&Problem - D2 - Codeforces
算法
Kk.08029 小时前
力扣 LCR 084.全排列||
算法·leetcode·职场和发展
环黄金线HHJX.9 小时前
龙虾钳足启发的AI集群语言交互新范式
开发语言·人工智能·算法·编辑器·交互
Omics Pro9 小时前
虚拟细胞:开启HIV/AIDS治疗新纪元的关键?
大数据·数据库·人工智能·深度学习·算法·机器学习·计算机视觉
旖-旎10 小时前
分治(快速选择算法)(3)
c++·算法·leetcode·排序算法·快速选择
_日拱一卒10 小时前
LeetCode:合并区间
算法·leetcode·职场和发展
xiaoye-duck10 小时前
【C++:哈希表封装】哈希表封装 myunordered_map/myunordered_set 实战:底层原理 + 完整实现
数据结构·c++·散列表
汀、人工智能10 小时前
[特殊字符] 第3课:最长连续序列
数据结构·算法·数据库架构·图论·bfs·最长连续序列
少许极端10 小时前
算法奇妙屋(四十一)-贪心算法学习之路 8
学习·算法·贪心算法
Kethy__10 小时前
计算机中级-数据库系统工程师-数据结构-图
数据结构·算法·软考··数据库系统工程师·计算机中级