|
| 1 | +/** |
| 2 | + * 918. Maximum Sum Circular Subarray |
| 3 | + * https://leetcode.com/problems/maximum-sum-circular-subarray/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * Given a circular integer array nums of length n, return the maximum possible sum of |
| 7 | + * a non-empty subarray of nums. |
| 8 | + * |
| 9 | + * A circular array means the end of the array connects to the beginning of the array. |
| 10 | + * Formally, the next element of nums[i] is nums[(i + 1) % n] and the previous element |
| 11 | + * of nums[i] is nums[(i - 1 + n) % n]. |
| 12 | + * |
| 13 | + * A subarray may only include each element of the fixed buffer nums at most once. |
| 14 | + * Formally, for a subarray nums[i], nums[i + 1], ..., nums[j], there does not exist |
| 15 | + * i <= k1, k2 <= j with k1 % n == k2 % n. |
| 16 | + */ |
| 17 | + |
| 18 | +/** |
| 19 | + * @param {number[]} nums |
| 20 | + * @return {number} |
| 21 | + */ |
| 22 | +var maxSubarraySumCircular = function(nums) { |
| 23 | + let [min, max, sum] = [nums[0], nums[0], nums[0]]; |
| 24 | + |
| 25 | + for (let i = 1, prevMin = nums[0], prevMax = nums[0]; i < nums.length; i++) { |
| 26 | + prevMax = Math.max(nums[i], prevMax + nums[i]); |
| 27 | + max = Math.max(max, prevMax); |
| 28 | + prevMin = Math.min(nums[i], prevMin + nums[i]); |
| 29 | + min = Math.min(min, prevMin); |
| 30 | + sum += nums[i]; |
| 31 | + } |
| 32 | + |
| 33 | + return max > 0 ? Math.max(max, sum - min) : max; |
| 34 | +}; |
0 commit comments