2020 bit java developers pen questions

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/Miaoshuowen/article/details/101568045

Casual working:
The first line of the input two integers n, m
the second row are sequentially input length n array
output indicates a number, the array of at least a minimum interval and m

Thinking:
Create an array SUM [] represents the current array index at least m and recording the smallest and return;
wherein the array SUM [] Algorithm: sum [m-1] is equal to the array in the first m elements and, then iterate, when <[i-1] + nums [i], the update min (minimum sum) when 0, sum [i] = sum ; sum [i-1]
when [i-1] sum> = 0 when Comparative sum [i-1] + nums [i] and a nums [im, i] is, sum [i] is equal to a smaller of the two, and then update the min (minimum sum)

public class Main {

	public int minSubArray(int[] nums, int m) {
		int[] sum = new int[nums.length];
		
		int M = 0;
		int sumtemp = 0;
		while (M < m) {

			sumtemp = sumtemp + nums[M];
			sum[m - 1] = sumtemp;
			M++;
		}
		int min = sum[m - 1];
		for (int i = m; i < nums.length; i++) {
			if (sum[i - 1] < 0) {
				sum[i] = sum[i - 1] + nums[i];
				min = Math.min(min, sum[i]);
			} else {
				int temp = 0;
				int z = i;
				for (int j = m; j > 0; j--) {

					temp = temp + nums[z--];
				}
				sum[i] = Math.min(temp, sum[i - 1] + nums[i]);
				min = Math.min(min, sum[i]);
			}

		}
		
				return min;

	}

	public static void main(String[] args) {

		Scanner in = new Scanner(System.in);
		int n = in.nextInt();
		int m = in.nextInt();
		int[] num = new int[n];

		for (int i = 0; i < n; i++) {
			num[i] = in.nextInt();

		}
		in.close();
		Main test = new Main();

		System.out.println(test.minSubArray(num, m));
	}

}

Guess you like

Origin blog.csdn.net/Miaoshuowen/article/details/101568045