w3resource

Java Array Exercises: Find minimum subarray sum of specified size in a given array of integers

Java Array: Exercise-69 with Solution

Write a Java program to find minimum subarray sum of specified size in a given array of integers.

Example:
Input :
nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10}
Output:
Sub-array size: 4
Sub-array from 0 to 3 and sum is: 10

Sample Solution:

Java Code:

import java.util.*;
class solution {

	public static int [] find_min_subarray_sum(int[] nums, int k)
	{
		int sub_arr_sum = 0;
		int min_sub_arr = Integer.MAX_VALUE;
		int last = 0;
		int[] result = new int[3];

		for (int i = 0; i < nums.length; i++)
		{
			sub_arr_sum += nums[i];

			if (i + 1 >= k)
			{
				if (min_sub_arr > sub_arr_sum)
				{
					min_sub_arr = sub_arr_sum;
					last = i;
				}

				sub_arr_sum -= nums[i + 1 - k];
			}
		}
		result[0] = last - k + 1;
		result[1] = last;
		result[2] = min_sub_arr;
		return result;		
	}

	public static void main(String[] args)
	{
		int[] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10};
		int k = 4;
        System.out.printf("\nOriginal array: "+Arrays.toString(nums));
		System.out.printf("\nSub-array size: %d", k);
		int [] result = find_min_subarray_sum(nums, k);
		System.out.printf("\nSub-array from %d to %d and sum is: %d", result[0], result[1], result[2]);
	}
}

Sample Output:

Original array: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sub-array size: 4
Sub-array from 0 to 3 and sum is: 10

Flowchart:

Flowchart: Find minimum subarray sum of specified size in a given array of integers.

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to create all possible permutations of a given array of distinct integers.
Next: Write a Java program to find the smallest length of a contiguous subarray of which the sum is greater than or equal to specified value. Return 0 instead.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Share this Tutorial / Exercise on : Facebook and Twitter

Java: Tips of the Day

countOccurrences

Counts the occurrences of a value in an array.

Use Arrays.stream().filter().count() to count total number of values that equals the specified value.

public static long countOccurrences(int[] numbers, int value) {
    return Arrays.stream(numbers)
            .filter(number -> number == value)
            .count();
}

Ref: https://bit.ly/3kCAgLb