maximum-subarray problem可以用divide-and-conquer的算法求解,算法复杂度为O(nlgn),另外,还有一种更简单的复杂度为O(n)的方法:
该解法的思路就来自于:《Introduction to Algorithms》中练习:4.1-5:
Use the following ideas to develop a nonrecursive, linear-time algorithm for the maximum-subarray problem. Start at the left end of the array, and progress toward
the right, keeping track of the maximum subarray seen so far. Knowing a maximum subarray of A[1..j] , extend the answer to find a maximum subarray ending at index j+1 by using the following observation: a maximum subarray of A[1.. j+1] is either a maximum subarray of A[1 .. j] or a subarray A[i .. j + 1], for some 1 <=i <=j + 1. Determine a maximum subarray of the form A[i .. j + 1] in constant time based on knowing a maximum subarray ending at index j .
public class MaximumSubArray {
void maxSubArray(int a[]) {
int max_so_far = a[0];
int max_ending_here = a[0];
int max_start_index = -1;
int max_end_index = 0;
for (int i = 1; i < a.length; i++) {
max_ending_here = max_ending_here + a[i];
if (max_ending_here < 0) {
max_ending_here = 0;
max_start_index = i;
} else if (max_so_far < max_ending_here) {
max_so_far = max_ending_here;
max_end_index = i;
}
}
if (max_so_far > 0)
System.out.println("The maximun sub array - size:" + max_so_far + ", from:" + max_start_index + " to:"
+ max_end_index);
else
System.out.println("All negative or zero, the maximum element is:" + max_so_far);
}
public static void main(String[] args) {
// int a[] = { 13, -3, -25, 20, -3, -16, -23, 18, 20, -7, 12, -5, -22, 15, -4, 7 };
// int a[] = { -1, -5, -4, -11, -21, -3 };
// int a[] = {0, 0, 0, 0, 0};
int a[] = {1, 2, -1, 3, 4};
MaximumSubArray ist = new MaximumSubArray();
ist.maxSubArray(a);
}
}
注意事项:
上面的代码先给max_so_far,max_ending_here赋了值,然后从index:1开始for循环,这样做的目的就是为了处理数组中都为负数或0的情况。
参考:
http://www.geeksforgeeks.org/archives/576