下面是我写的获取最大序列的方法,最终值是对的,但是中间有几条语句执行有问题
import java.util.ArrayList;import java.util.Collections;
import java.util.HashMap;
public class MaxList {
public static void main(String[] args) {
int[] array = new int[]{-1,2,3,4,-5,6,7};
maxlist(array);
}
public static ArrayList<Integer> maxlist(int[] array) {
ArrayList<Integer> max = new ArrayList<>();//用于接收最大序列
ArrayList<Integer> receive = new ArrayList<>();//用于接收所有最大序列的和
HashMap<Integer, ArrayList<Integer>> hash = new HashMap<>();//用于存储返回的序列和它的索引值
if (array.length == 0)
return null;
else if (array.length == 1) {
max.add(array[0]);
System.out.println(max);
return max;
}
max.add(array[0]);
receive.add(Sum(max));
for (int i = 1; i < array.length; i++) {
if (Sum(max) > 0) {
max.add(array[i]);
System.out.println(Sum(max));
receive.add(Sum(max));//如果前面的序列大于0,那么添加后面的一个数组元素并且存储当前集合的和
System.out.println(receive);
System.out.println(max);
hash.put(Sum(max), max);
System.out.println(hash); //执行结果是:
}
else if (Sum(max) <= 0) {
//max.add(array[i]);
//System.out.println(max);
max.clear();
receive.clear();
max.add(array[i]);
//System.out.println("max:" + max);
receive.add(array[i]);//如果前面的序列小于等于0,那么直接将当前数组的值作为receive的元素
//System.out.println(receive);
hash.put(array[i], max);
System.out.println(hash);
System.out.println("=======================");
}
}
System.out.println("=======================");
//Collections.sort(receive);
//System.out.println(receive);
System.out.println(hash);
//System.out.println(receive.size());
System.out.println(hash.get(receive.get(receive.size() - 1 )));//求出最大序列
return hash.get(receive.get(receive.size() - 1));
}
public static int Sum(ArrayList<Integer> array){
int sum = 0;
for (int i = 0; i < array.size(); i++) {
sum += array.get(i);
}
return sum;
}
}