题目
给定一个序列,给出最大子序列的和。
解答
public class maxSubSum {
public static int maxSubSum1(int [] a){
int maxSum = 0;
for (int i = 0; i < a.length; i++) {
for(int j=i;j<a.length;j++){
int thisSum = 0;
for (int k = i; k <=j; k++) {
thisSum += a[k];
}
if (thisSum > maxSum){
maxSum = thisSum;
}
}
}
return maxSum;
}
public static int maxSubSum2(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;
}
public static int maxSubSum3(int [] a){
int maxSum = 0,thisSum = 0;
for (int j = 0; j < a.length; j++) {
thisSum += a[j];
if (thisSum > maxSum){
maxSum = thisSum;
// System.out.println("sss:"+maxSum);
}else if(thisSum < 0){
thisSum = 0;// 相当于当前面的队列和为负数时,直接舍弃掉
}
}
return maxSum;
}
public static void main(String[] args) {
int [] nums = {-1,3,-4,12,-4,-2};
System.out.println(maxSubSum1(nums));// 12
System.out.println(maxSubSum2(nums));// 12
System.out.println(maxSubSum3(nums));// 12
}
}