分类: Java
2010-10-05 21:54:40
求最大子串和,时间复杂度为O(n)
/**
* @author Kevin Alps
*/
public class Test {
/**
* @param src
* @return 返回最大连续子串和,时间复杂度O(n)
*/
public static int max(int[] src) {
int sum = src[0];
int minsum = src[0];
int maxsum = src[0];
int sum1 = src[0];
int sum2 = src[0];
int max = src[0];
for (int i = 1; i < src.length; i++) {
sum += src[i];
if (sum1 > 0) {
sum1 += src[i];
} else {
sum1 = src[i];
}
if (sum2 < 0) {
sum2 += src[i];
} else {
sum2 = src[i];
}
if (sum1 > maxsum) {
maxsum = sum1;
}
if (sum2 < minsum) {
minsum = sum2;
}
}
max = maxsum > sum - minsum ? maxsum : sum - minsum;
if(minsum == sum) {
max = maxsum;
}
return max;
}
public static void main(String[] args) {
int src[] = { 1, 2, 3, 4, -5, 6, 7, 8 };
System.out.println(Test.max(src));
}
}