Leetcode 918. Maximum Sum Circular Subarray (滑动窗口+单调队列好题)

  1. Maximum Sum Circular Subarray
    Medium

Given a circular integer array nums of length n, return the maximum possible sum of a non-empty subarray of nums.

A circular array means the end of the array connects to the beginning of the array. Formally, the next element of numsi is nums(i + 1) % n and the previous element of numsi is nums(i - 1 + n) % n.

A subarray may only include each element of the fixed buffer nums at most once. Formally, for a subarray numsi, numsi + 1, ..., numsj, there does not exist i <= k1, k2 <= j with k1 % n == k2 % n.

Example 1:

Input: nums = 1,-2,3,-2

Output: 3

Explanation: Subarray 3 has maximum sum 3.

Example 2:

Input: nums = 5,-3,5

Output: 10

Explanation: Subarray 5,5 has maximum sum 5 + 5 = 10.

Example 3:

Input: nums = -3,-2,-3

Output: -2

Explanation: Subarray -2 has maximum sum -2.

Constraints:

n == nums.length

1 <= n <= 3 * 104

-3 * 104 <= numsi <= 3 * 104

解法1:

不用滑动窗口和单调队列。实际上我们找连续子数组最大和 与 sum - 连续子数组最小和 之间的最大值就可以了。

cpp 复制代码
class Solution {
public:
    int maxSubarraySumCircular(vector<int>& nums) {
        int sum = 0, currMaxSum = 0, currMinSum = 0;
        int gMaxSum = INT_MIN, gMinSum = INT_MAX;
        for (auto num : nums) {
            sum += num;
            currMaxSum = max(currMaxSum + num, num);
            gMaxSum = max(gMaxSum, currMaxSum);
            currMinSum = min(currMinSum + num, num);
            gMinSum = min(gMinSum, currMinSum);
        }
        //if all negative
        if (gMinSum == sum) return gMaxSum;
        return max(gMaxSum, sum - gMinSum);
    }
};

解法2:滑动窗口 + 单调队列

相关推荐
Navigator_Z1 小时前
LeetCode //C - 1203. Sort Items by Groups Respecting Dependencies
c语言·算法·leetcode
临床数据科学和人工智能兴趣组1 小时前
R语言中,列表是一种非常灵活的数据结构,它可以存储不同类型的对象,如向量、矩阵、数据框、甚至其他列表
数据结构·数据库·r语言·r语言-4.2.1·临床试验
我变成萤火虫2 小时前
2026 ICPC沈阳邀请赛Vp补题
数据结构·c++·算法·贪心算法·stl·排序算法·动态规划
神威难绷泪2 小时前
数据结构:二叉树
数据结构·二叉树
风起洛阳@不良使2 小时前
中级软考(软件攻城狮)第3章知识点——数据结构与数据运算(线性结构+非线性结构)
数据结构·算法·链表
AndrewHZ2 小时前
图像处理入门009 | OpenCV 图像读取与显示:imread/imshow 全解析
图像处理·python·opencv·算法·计算机视觉·图像显示
学计算机的计算基2 小时前
TCP 传输层硬核整理:三次握手、四次挥手、拥塞控制一次讲透
java·网络·笔记·网络协议·算法
索西引擎2 小时前
【数据结构】B树与B+树:结构性质、对比分析与磁盘优化机理
数据结构·b树
xx~t2 小时前
嵌入式学习22
数据结构·学习·算法·排序算法