输入一个整形数组,数组里有正数也有负数,数组中一个或连续的多个整数组成一个子数组,求所有子数组的和的最大值
public class Test5 {
public static void main(String[] args) {
int[] num = {1,-2,3,10,-4,7,2,-5};
List<Integer> list = new ArrayList<Integer>();
function(num, 0, list);
int max = 0;
for (Integer integer : list) {
if (integer>max) {
max = integer;
}
}
System.out.println(max);
}
public static void function(int[] intArray,int start,List<Integer> list){
if (start>intArray.length) {
return;
}
for (int i = start; i < intArray.length; i++) {
int sum = 0;
for (int j = start; j <=i; j++) {
sum = sum+intArray[j];
}
list.add(sum);
}
function(intArray, start+1, list);
}
}
数组中连续的子数组最大的和
public class Test6 {
public static void main(String[] args) {
int[] num = {1,-2,3,10,-4,7,2,-5};
//int[] num = {1,-2,3,10,-4,10,2,-5};
System.out.println(maxSum(num));
}
public static int maxSum(int[] num){
int curSum = 0;
int curMaxSum = -99999999;
int start = 0;
int end = 0;
for(int i=0;i<num.length;i++){
if(curSum<=0){
curSum = num[i];
start = i;
}
else{
curSum += num[i];
}
if(curSum>curMaxSum){
curMaxSum = curSum;
end = i;
}
}
return curMaxSum;
}
}