import java.util.Arrays;
/**
* 给定一个数组list,找出m长度的子数组值总和的最大值
* @author Demon-HY
* @date 2019-4-30
*/
public class Test {
public static void main(String[] args) {
Integer[] list = new Integer[]{1, 3, 5, 23, 12, 1, 54, 23, 5, 32, 52, 52, 1, 1, 1};
getSubListMaxSum(list, 4);
}
private static void getSubListMaxSum(Integer[] list, int m) {
// m 长度的子数组
Integer[] subList = new Integer[m];
// 子数组元素之和最大值
Integer subListSumMax = 0;
// 填充子数组
for (int subListIndex = 0; subListIndex < subList.length; subListIndex++) {
subListSumMax += list[subListIndex];
subList[subListIndex] = list[subListIndex];
}
System.out.println("初始数组:" + Arrays.toString(subList) + ", 最大值:" + subListSumMax);
// 新的子数组的最大值
Integer newSubListSum;
// 遍历 list[m] 下标开始的数据,比较新旧子数组的值
for (int listIndex = m; listIndex < list.length; listIndex++) {
// 将子数组中的第一个元素取出,然后从list中读取一个新值
// 用上一轮记录的 子数组元素之和最大值 - 子数组第一个值 + list中新值 = 新的子数组的最大值
newSubListSum = subListSumMax - subList[0] + list[m];
if (subListSumMax < newSubListSum) {
subListSumMax = newSubListSum;
}
// 用来截取新的子数组
int listSubIndex = listIndex - m + 1;
// 更新subList中的数据
for (int subListIndex = 0; subListIndex < m; subListIndex++) {
subList[subListIndex] = list[listSubIndex++];
}
System.out.println("中间数组:" + Arrays.toString(subList) + ", 最大值:" + subListSumMax);
}
System.out.println("结束数组:" + Arrays.toString(subList) + ", 最大值:" + subListSumMax);
}
}