leetcode918.环形子数组的最大和

参考了灵神的题解,然后只要用动态规划求解子数组的最大和和最小和就可以

java 复制代码
class Solution {
    public int maxSubarraySumCircular(int[] nums) {
        int sum = nums[0];
        //变量记录普通子数组的最大和
        int currentMax = nums[0];
        int globalMax = nums[0];
        //变量记录普通子数组的最小和
        int currentMin = nums[0];
        int globalMin = nums[0];

        //动态规划求解普通子数组的最大和和最小和
        for (int i = 1; i < nums.length; i++) {
            sum += nums[i];
            currentMax = Math.max(currentMax + nums[i], nums[i]);
            globalMax = Math.max(globalMax, currentMax);
            currentMin = Math.min(currentMin + nums[i], nums[i]);
            globalMin = Math.min(globalMin, currentMin);
        }
        return sum == globalMin ? globalMax : Math.max(globalMax, sum - globalMin);
    }
}
相关推荐
m0_748248024 分钟前
揭开 C++ vector 底层面纱:从三指针模型到手写完整实现
开发语言·c++·算法
七夜zippoe14 分钟前
Ascend C流与任务管理实战:构建高效的异步计算管道
服务器·网络·算法
Greedy Alg31 分钟前
LeetCode 208. 实现 Trie (前缀树)
算法
还是码字踏实31 分钟前
基础数据结构之哈希表:两数之和(LeetCode 1 简单题)
数据结构·leetcode·散列表
Kt&Rs32 分钟前
11.5 LeetCode 题目汇总与解题思路
数据结构·算法·leetcode
还是码字踏实34 分钟前
基础数据结构之数组的前缀和技巧:和为K的子数组(LeetCode 560 中等题)
算法·leetcode·前缀和·哈希字典
沙威玛_LHE4 小时前
树和二叉树
数据结构·算法
py有趣6 小时前
LeetCode算法学习之两数之和 II - 输入有序数组
学习·算法·leetcode
夏鹏今天学习了吗6 小时前
【LeetCode热题100(62/100)】搜索二维矩阵
算法·leetcode·矩阵
吃着火锅x唱着歌8 小时前
LeetCode 1128.等价多米诺骨牌对的数量
算法·leetcode·职场和发展