> For the complete documentation index, see [llms.txt](https://timmybeeflin.gitbook.io/cracking-leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://timmybeeflin.gitbook.io/cracking-leetcode/dynamic-programming/918.-maximum-sum-circular-subarray-kadane-algo.md).

# 918. Maximum Sum Circular Subarray (kadane-algo)

case1: noneCircularMaxSum

case2: circularMaxSum

![](/files/IfJBQdjsHVsw8TLU2Asg)

corner case, all numbers are negative, minSum = total, so total - minsum = 0

result will be wrong : max(maxSum, 0) = 0, but we should return maxSum,&#x20;

so when total - minsum = 0 (circularMaxSum == 0), just return maxSum (noneCircularMaxSum)

![](/files/vFD2s4VqRr8ZYEh8E9OK)

T: O(n)

S: O(1)

```java
class Solution {
    public int maxSubarraySumCircular(int[] nums) {
        int noneCircularMaxSum = kadane(nums);
        int total = 0;
        for (int i = 0; i < nums.length; i++) {
            total += nums[i];
            nums[i] = -nums[i];
        }
        int circularMaxSum = total + kadane(nums);
        if (circularMaxSum == 0) {
            return noneCircularMaxSum;
        }
        return Math.max(noneCircularMaxSum, circularMaxSum);
        
    }
    private int kadane(int[] nums) {
        int max = Integer.MIN_VALUE;
        int sum = 0;
        for (int num : nums) {
            sum += num;
            max = Math.max(max, sum);
            if (sum < 0) {
                sum = 0;
            }
        }
        return max;
    }
}

/*






  0. 1 2 3 4.  5
  5 -3 5 5 -3  5
0 5  2 7 12 9 14


  1,-2,3,-2 1,-2,3,-2
0 1 -1 2 0. 1.-1 2. 0


  -3 -2 -3 -3 -2 -3 
0 -3 -5 -8 -11 -13 -16

5  2 7 12 9 14


  [-2,-3,-1, -2, -3, -1]
0  -2 -5 -6  -8 -11. -12
*/
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://timmybeeflin.gitbook.io/cracking-leetcode/dynamic-programming/918.-maximum-sum-circular-subarray-kadane-algo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
