需求:
一贫如洗的樵夫阿里巴巴在去砍柴的路上,无意中发现了强盗集团的藏宝地,藏宝地有编号从0~N的箱子,每个箱子上面贴有一个数字。 阿里巴巴念出一个咒语数字k(k
输入描述 第一行输入一个数字字串,数字之间使用逗号分隔,例如:2,10,-3,-8,40,5 第二行输入咒语数字,例如:4,咒语数字大小小于宝箱的个数输出描述 最大值
输入:
2,10,-3,-8,40,5 ->数字字符串
4 ->咒语数字大小
输出:
39
编码:
- 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;
- }
- }
效果:
