918. 环形子数组的最大和
918. 环形子数组的最大和
🟠 🔖 队列 数组 分治 动态规划 单调队列 🔗 力扣 LeetCode
题目
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.length1 <= n <= 3 * 10^4-3 * 104 <= nums[i] <= 3 * 10^4
题目大意
给定一个长度为 n 的环形整数数组 nums ,返回 nums 的非空 子数组 的最大可能和。
环形数组 意味着数组的末端将会与开头相连呈环状。形式上, nums[i] 的下一个元素是 nums[(i + 1) % n] , nums[i] 的前一个元素是 nums[(i - 1 + n) % n] 。
子数组 最多只能包含固定缓冲区 nums 中的每个元素一次。形式上,对于子数组 nums[i], nums[i + 1], ..., nums[j] ,不存在 i <= k1, k2 <= j 其中 k1 % n == k2 % n 。
示例 1:
输入: nums = [1,-2,3,-2]
输出: 3
解释: 从子数组 [3] 得到最大和 3
示例 2:
输入: nums = [5,-3,5]
输出: 10
解释: 从子数组 [5,5] 得到最大和 5 + 5 = 10
示例 3:
输入: nums = [3,-2,2,-3]
输出: 3
解释: 从子数组 [3] 和 [3,-2,2] 都可以得到最大和 3
提示:
n == nums.length1 <= n <= 3 * 10^4-3 * 104 <= nums[i] <= 3 * 10^4
解题思路
要解决这个问题,可以考虑两种情况:
- 普通子数组:可以直接使用经典的 Kadane’s Algorithm 来找到非循环的最大子数组和。
- 跨越首尾的子数组:这个子数组可以被理解为,总和减去一个最小的子数组和(即,找到整个数组的和,再减去中间的一个子数组,保留数组两端部分作为最大子数组和)。要实现这一点,需要求出最小子数组和。
因此,解题分为三步:
- 计算非循环子数组的最大和:使用 Kadane's 算法来找到子数组的最大和
maxSum. - 计算最小子数组和:使用 Kadane's 算法的变种,找出子数组的最小和
minSum,然后用整个数组的和totalSum减去该最小和。这样得到跨越首尾的子数组和totalSum - minSum。 - 考虑特殊情况:当所有元素都是负数时,跨越首尾的子数组和可能会无效,因为整个数组的和
totalSum会等于minSum。在这种情况下,返回maxSum即可。
复杂度分析
- 时间复杂度:
O(n),因为只遍历数组三次(分别求最大子数组和、最小子数组和,以及总和),每次遍历需要O(n)时间。 - 空间复杂度:
O(1),因为只使用了常数空间来存储若干变量,不需要额外的数组或其他数据结构。
代码
/**
* @param {number[]} nums
* @return {number}
*/
var maxSubarraySumCircular = function (nums) {
const totalSum = nums.reduce((a, b) => a + b, 0);
const getMaxSum = () => {
let max = nums[0],
maxEndingHere = nums[0];
for (let i = 1; i < nums.length; i++) {
maxEndingHere = Math.max(nums[i], maxEndingHere + nums[i]);
max = Math.max(maxEndingHere, max);
}
return max;
};
const getMinSum = () => {
let min = nums[0],
minEndingHere = nums[0];
for (let i = 1; i < nums.length; i++) {
minEndingHere = Math.min(nums[i], minEndingHere + nums[i]);
min = Math.min(minEndingHere, min);
}
return min;
};
const maxSum = getMaxSum();
const minSum = getMinSum();
if (maxSum < 0) return maxSum;
return Math.max(maxSum, totalSum - minSum);
};
