Huawei OD machine test: Alibaba looking for a golden treasure chest (V) (Java source code)

Alibaba looking for a golden treasure chest (V)

topic description

The impoverished woodcutter Ali Baba stumbled across the treasure trove of the robber group on his way to cut firewood. There are boxes numbered from 0 to N in the treasure trove, and each box has a number attached to it.
Alibaba reads a mantra 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

  • 1 ≤ number of digits in string ≤ 100000 
  • -10000 ≤ each number ≤ 10000
Enter the spell number in the second line, for example: 4, the size of the spell number is smaller than the number of treasure chests

output description

The maximum sum of k consecutive treasure chest numbers, for example: 39

Example

enter 2,10,-3,-8,40,5
4
output 39
illustrate none
enter 8
1
output 8
illustrate none

topic analysis

  1. To get the maximum sum of k consecutive treasure chest numbers, you can use a sliding window to solve
    1.1. Define two pointers, and first find the sum between the two pointers.
    1.2 Move the two pointers to the right, and subtract the removed one from the previous sum (left side), plus the shifted-in (right side), so that the sum of the next continuous K interval is obtained. Then use the comparison method, if the sum of this interval is larger than the previous one, then record it, otherwise continue to move to the right
  2. The specific logic can be coded

sample code

import java.util.Scanner;

public class T67 {
    
    
	public static void main(String[] args) {
    
    
		Scanner sc = new Scanner(System.in);
		String input = sc.nextLine();
		String strArr[] = input.split(",");
		int nums[] = new int[strArr.length];
		for (int i = 0; i < strArr.length; i++) {
    
    
			nums[i] = Integer.parseInt(strArr[i]);
		}
		int num = sc.nextInt();
		int left = 0;
		int right = num - 1;
		int tempSum = 0;
		for (int i = left; i <= right; i++) {
    
    
			tempSum += nums[i];
		}
		int max = tempSum;
		// 右移
		while (right < nums.length - 1) {
    
    
			tempSum -= nums[left++];
			tempSum += nums[++right];
			if (tempSum > max)
				max = tempSum;
		}
		System.out.println(max);
	}
}

screenshot of code running
insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/qq_33183456/article/details/131321510