Problem Summary
Problem 1: Maximum Subarray II
Given an array of integers, find two non-overlapping subarrays which have the largest sum. The subarray should contain at least one number and the numbers in each subarray should be contiguous.
Problem 2: Maximum Subarray Difference
Given an array of integers, find two non-overlapping subarrays A and B, such that |SUM(A) - SUM(B)| is the largest.
The subarray should contain at least one number and the numbers in each subarray should be contiguous.
Calculate the largest difference.
Solution
Problem 1:
Let us denote the given array with A[0]A[1]…A[N-1].
Define
- f[i] as the maximal sum of subarray ending at i or before i,
- g[i] as the maximal sum of two subarrays of which the second one ends at i.
So the answer is max{g[i]}, i = 0,1,…,N-1.
If we use min_sum to indicate the minimum cumulative sum before i, we have
f[i] = max{f[i-1], cur_sum - min_sum}
g[i] = max{g[i-1], f[i-1]} + A[i]
The time complexity is O(N); the space complexity is O(1), since we only need f[i-1] and g[i-1], instead of f[0]…f[i-1] and g[0]…g[i-1], when we calculate f[i] and g[i].
Problem 2:
This is easier after we solved problem 1.
Define
- f[i][0] as the maximal sum of subarray ending at i or before i,
- f[i][1] as the minimal sum of subarray ending at i or before i,
- g[i][0] as the maximal difference of two subarrays of which the second one ends at i.
- g[i][1] as the minimal difference of two subarrays of which the second one ends at i.
So the answer is max{abs(g[i][j])}, i = 0,1,…,N-1, j = 0,1.
We have
f[i][0] = max{f[i-1][0], cur_sum - min_sum}
f[i][1] = min{f[i-1][1], cur_sum - max_sum}
g[i][0] = max{g[i-1][0], -f[i-1][1]} + nums[i-1];
g[i][1] = min{g[i-1][1], -f[i-1][0]} + nums[i-1];
The time complexity is O(N); the space complexity is O(1).
Code 1: Maximum Subarray II, O(1) space
|
|
Code 2: Maximum Subarray II, O(N) space
|
|
Code 3: Maximum Subarray Difference
|
|