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 nums[i] is nums[(i + 1) % n] and the previous element of nums[i] 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 nums[i], nums[i + 1], ..., nums[j], 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 <= nums[i] <= 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:滑动窗口 + 单调队列

相关推荐
jjyangyou2 分钟前
物联网核心安全系列——物联网安全需求
物联网·算法·安全·嵌入式·产品经理·硬件·产品设计
van叶~19 分钟前
算法妙妙屋-------1.递归的深邃回响:二叉树的奇妙剪枝
c++·算法
简简单单做算法20 分钟前
基于Retinex算法的图像去雾matlab仿真
算法·matlab·图像去雾·retinex
云卓SKYDROID35 分钟前
除草机器人算法以及技术详解!
算法·机器人·科普·高科技·云卓科技·算法技术
半盏茶香1 小时前
【C语言】分支和循环详解(下)猜数字游戏
c语言·开发语言·c++·算法·游戏
徐子童1 小时前
双指针算法习题解答
算法
想要打 Acm 的小周同学呀1 小时前
LRU缓存算法
java·算法·缓存
劲夫学编程2 小时前
leetcode:杨辉三角
算法·leetcode·职场和发展
毕竟秋山澪2 小时前
孤岛的总面积(Dfs C#
算法·深度优先
浮生如梦_4 小时前
Halcon基于laws纹理特征的SVM分类
图像处理·人工智能·算法·支持向量机·计算机视觉·分类·视觉检测