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

            


        
相关推荐
tankeven2 小时前
HJ93 数组分组
c++·算法
Σίσυφος19002 小时前
LM 在 PnP(EPnP / P3P)的应用
算法
陈天伟教授2 小时前
人工智能应用- 人工智能交叉:01. 破解蛋白质结构之谜
人工智能·神经网络·算法·机器学习·推荐算法
LightYoungLee3 小时前
General-behavior interview tutorials
算法
I_LPL3 小时前
day34 代码随想录算法训练营 动态规划专题2
java·算法·动态规划·hot100·求职面试
We་ct3 小时前
LeetCode 105. 从前序与中序遍历序列构造二叉树:题解与思路解析
前端·算法·leetcode·链表·typescript
万象.4 小时前
redis集群算法,搭建,故障处理及扩容
redis·算法·哈希算法
plus4s4 小时前
2月19日(85-87题)
c++·算法
Desirediscipline4 小时前
cerr << 是C++中用于输出错误信息的标准用法
java·前端·c++·算法