> For the complete documentation index, see [llms.txt](https://leetcodebook-1.gitbook.io/top-interview-150/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://leetcodebook-1.gitbook.io/top-interview-150/kadane/maximum-sum-circular-subarray.md).

# 环形子数组的最大和

题目链接: <https://leetcode.cn/problems/maximum-sum-circular-subarray>

## 解题思路：

将环形数组拆成两个普通数组，然后分别求出两个数组的最大子序和，最后取两个最大子序和的较大值作为环形子数组的最大和

**具体实现：**

1. 遍历数组，计算当前的最大和、最小和、最大子序和、最小子序和和数组的和
2. 如果数组的和等于最小子序和，则说明数组中所有元素都是负数，此时最大子序和即为最大值
3. 否则，最大子序和为 `max(maxSum, sum-minSum)`

```go
func maxSubarraySumCircular(nums []int) int {
	maxSum, minSum := nums[0], nums[0]
	curMax, curMin := nums[0], nums[0]
	sum := nums[0]

	// 遍历数组，计算当前的最大和、最小和、最大子序和、最小子序和和数组的和
	for i := 1; i < len(nums); i++ {
		sum += nums[i]                        // 计算数组的和
		curMax = max(curMax+nums[i], nums[i]) // 计算当前的最大和
		maxSum = max(maxSum, curMax)          // 计算最大子序和
		curMin = min(curMin+nums[i], nums[i]) // 计算当前的最小和
		minSum = min(minSum, curMin)          // 计算最小子序和
	}

	// 如果数组的和等于最小子序和，则说明数组中所有元素都是负数，此时最大子序和即为最大值
	if sum == minSum {
		return maxSum
	}

	// 否则，最大子序和为 max(maxSum, sum-minSum)
	return max(maxSum, sum-minSum)
}

func max(a, b int) int {
	if a > b {
		return a
	}

	return b
}

func min(a, b int) int {
	if a > b {
		return b
	}

	return a
}
```

## 复杂度分析

* **时间复杂度：** 时间复杂度是 $$O(n)$$
* **空间复杂度：** 空间复杂度是 $$O(1)$$


---

# 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 by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://leetcodebook-1.gitbook.io/top-interview-150/kadane/maximum-sum-circular-subarray.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
