最大连续子数组
给定一个数组A【0,1 .......,n-1】,求A的连续子数组,使得该子数组的和最大。
例如:
数组:1,-2,3,10,-4,7,2,-5
最大子数组:3,10,-4,7,2
分别采用暴力法、分治法、分析法、动态规划法解决
1> 暴力法
public class MaxContiSubArray {
//运用暴力法进行求解
public static void main(String[] args) {
int[] a = {1,-2,3,10,-4,7,2,-5};
System.out.println(maxSubArray(a));
}
public static int maxSubArray(int[]a) {
int maxSum = a[0];
int currSum;
for(int i = 0 ; i < a.length; i ++ ) {
for(int j = i+1 ; j < a.length; j ++) {
currSum = 0;
for(int k = i; k <= j; k ++) {
currSum += a[k];
}
if(currSum > maxSum) {
maxSum = currSum;
}
}
}
return maxSum;
}
}