# Maximum Subarray Ii

## Maximum Subarray Ii

## 题目地址

<https://www.lintcode.com/problem/maximum-subarray-ii/description>

## 题目描述

```
Given an array of integers, find two non-overlapping subarrays which have the largest sum.
The number in each subarray should be contiguous.
Return the largest sum.
```

## 代码

### Approach #1

```java
public class Solution {
  public int maxTwoSubArray(ArrayList<Integer> nums) {
    if (nums == null || nums.isEmpty()) return -1;
    int size = nums.size();
    int[] maxSubArrayFront = new int[size];
    forwardTraversal(nums, maxSubArrayFront);

    int[] maxSubArrayBack = new int[size];
    backwardTraversal(nums, maxSubArrayBack);

    int maxTwoSub = Integer.MIN_VALUE;
    for (int i = 0; i < size - 1; i++) {
      maxTwoSub = Math.max(maxTwoSub, maxSubArrayFront[i] + maxSubArrayBack[i + 1]);
    }

    return maxTwoSub;
  }

  private void forwardTraversal(List<Integer> nums, int[] maxSubArray) {
    int sum = 0, minSum = 0, maxSub = Integer.MIN_VALUE;
    int size = nums.size();
    for (int i = 0; i < size; i++) {
      minSum = Math.min(minSum, sum);
      sum += nums.get(i);
      maxSub = Math.max(maxSub, sum - minSum);
      maxSubArray[i] = maxSub;
    }
  }

  private void backwardTraversal(List<Integer> nums, int[] maxSubArray) {
    int sum = 0, minSum = 0, maxSub = Integer.MIN_VALUE;
    int size = nums.size();
    for (int i = size - 1; i >= 0; i--) {
      minSum = Math.min(minSum, sum);
      sum += nums.get(i);
      maxSub = Math.max(maxSub, sum - minSum);
      maxSubArray[i] = maxSub;
    }
  }

}
```


---

# 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://wentao-shao.gitbook.io/leetcode/array/maximum-subarray-ii.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.
