# Maximum Subarray

{% embed url="<https://leetcode.com/problems/maximum-subarray/>" %}

## Solution 1 (Go)

```go
func maxSubArray(nums []int) int {
    if len(nums) == 1 {
        return nums[0]
    }
    max, result := nums[0], 0
    for i := 0; i < len(nums); i++ {
        result += nums[i]
        // only update result when it can be increased
        if result > max {
            max = result
        }
        if result < 0 {
            result = 0
        }
    }
    return max
}
```

## Solution 2 (Go)

```go
func Max(x, y int) int {
    if x < y {
        return y
    }
    return x
}

func maxSubArray(nums []int) int {
    if len(nums) == 1 {
        return nums[0]
    }
    dp, result := make([]int, len(nums)), nums[0]
    // base case
    dp[0] = nums[0]
    // recursive relation
    for i := 1; i < len(nums); i++ {
        dp[i] = Max(dp[i-1] + nums[i], nums[i])
        result = Max(result, dp[i])
    }
    return result
}
```

## Solution 3 (Java)

```java
class Solution {
    public int maxSubArray(int[] nums) {
        int currSum = nums[0];
        int maxSum = nums[0];
        
        for (int i = 1; i < nums.length; i++) {
            // if currSum is reset to nums[i], it means that we start at nums[i] now
            currSum = Math.max(nums[i], currSum + nums[i]);
            maxSum = Math.max(maxSum, currSum);
        }
        return maxSum;
    }
}
```


---

# Agent Instructions: 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://blog.yushunchen.com/algo/array/maximum-subarray.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.
