need:
Alibaba, a impoverished woodcutter, accidentally discovered the treasure trove of a bandit group on his way to cut firewood. The treasure trove contained boxes numbered from 0 to N, and each box had a number on it. Alibaba recites a spell number k (k<N), finds the maximum value of the sum of k consecutive treasure chest numbers, and outputs the maximum value.
Enter description Enter a string of numbers in the first line, separated by commas, for example: 2,10,-3,-8,40,5 In the second line, enter the spell number, for example: 4. The size of the spell number is smaller than the number of treasure chests.Output description maximum value
enter:
2,10,-3,-8,40,5 ->numeric string
4 ->Spell number size
Output:
39
coding:
public class AiLibaba{
public static void main(String[] args) {
//1.列表数据
Scanner scanner = new Scanner(System.in);
System.out.print("输入一个数字字串:");
String str = scanner.nextLine();
//字符串数组
String[] strNum = str.split(",");
//集合对象
List<Integer> list = new ArrayList<>();
for (int i = 0; i < strNum.length; i++) {
list.add(new Integer(strNum[i])); //添加到集合中
}
//2.求出最大值
System.out.print("输入咒语数字:");
int numK = scanner.nextInt();
//调用方法
int max = showMax(list, numK);
System.out.println("最大值:" + max);
}
/**
*
* @param list 列表数据
* @param numK 咒语数字
* @return
*/
private static int showMax(List<Integer> list, int numK) {
// (1)定义两个指针,先求两个指针之间的和
int left = 0; //左边
int right = numK - 1; //右边
//累计和
int sum = 0;
for (int i = left; i <= right; i++) {
sum += list.get(i); //累计
}
//最大值
int max = sum;
// (2) 两个指针右移,前面的和减掉移出去的(左侧),加上移入的(右侧)这样便得到下一个连续K区间的和。
//右移
while (right < list.size() - 1) {
sum -= list.get(left++);
sum += list.get(++right);
// 再用比较的方式,如果这个区间和比之前的大,那么就记录,否则继续右移
if (sum > max)
max = sum;
}
return max;
}
}
Effect: