Skip to content

Commit 1be29d7

Browse files
committed
Add solution #918
1 parent c2fcccb commit 1be29d7

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -488,6 +488,7 @@
488488
912|[Sort an Array](./0912-sort-an-array.js)|Medium|
489489
914|[X of a Kind in a Deck of Cards](./0914-x-of-a-kind-in-a-deck-of-cards.js)|Medium|
490490
916|[Word Subsets](./0916-word-subsets.js)|Medium|
491+
918|[Maximum Sum Circular Subarray](./0918-maximum-sum-circular-subarray.js)|Medium|
491492
922|[Sort Array By Parity II](./0922-sort-array-by-parity-ii.js)|Easy|
492493
925|[Long Pressed Name](./0925-long-pressed-name.js)|Easy|
493494
926|[Flip String to Monotone Increasing](./0926-flip-string-to-monotone-increasing.js)|Medium|
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
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

Comments
 (0)