给定整数A1 A2.....An,求∑_(k=i)^j Ak的最大值
package chapter2;
public class Demo1 {
public static void main(String[] args) {
int a[] = { -2, 11, -4, 13, -5, -2 };
System.out.println(maxSubSum(a));
}
public static int maxSubSum(int[] a) {
int maxSum = 0;
for (int i = 0; i < a.length; i++) {
int thisSum = 0;
for (int j = i; j < a.length; j++) {
thisSum += a[j];
if (thisSum > maxSum) {
maxSum = thisSum;
}
}
}
return maxSum;
}
}
第二种方法:
package chapter2;
public class Demo1 {
public static void main(String[] args) {
int a[] = { -2, 11, -4, 13, -5, -2 };
System.out.println(maxSubSum(a));
}
public static int maxSubSum(int[] a) {
int maxSum = 0;
int thisSum = 0;
for (int i = 0; i < a.length; i++) {
thisSum += a[i];
if (thisSum > maxSum) {
maxSum = thisSum;
} else if (thisSum < 0) {
thisSum = 0;
}
}
return maxSum;
}
}