1、求最大子數組和。輸入一個整形數組,數組中連續的一個或多個整數組成一個子數組,每個子數組都有一個和,求所有子數組和的最大值。
例:輸入的數組爲1,-2,3,10,-4,7,2,-5。和最大的子數組爲3,10,-4,7,2。因此輸出該子數組的和爲18。
代碼如下:
**方法一**(暴力法)
public class test005 {
public static void main(String[] args) {
int[] a = new int[]{1,-2, 3,10, -4, 7, 2, -5};
int res = maxSum(a);
System.out.println("所有子數組和的最大值爲:"+res);
}
private static int maxSum(int[] a) {
if(a==null || a.length ==0){
return 0;
}
int max = a[0];
for(int i=0; i<a.length; i++){
int temp = 0;
for(int j=i; j<a.length; j++){
temp+=a[j];
if(temp>max){
max = temp;
}
}
}
return max;
}
}
算法複雜度爲O(n^2)
**方法二**
public class test005 {
publ