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?



Java: Tips of the Day

Different between parseInt() and valueOf() in java?

Well, the API for Integer.valueOf(String) does indeed say that the String is interpreted exactly as if it were given to Integer.parseInt(String). However, valueOf(String) returns a new Integer() object whereas parseInt(String) returns a primitive int.

If you want to enjoy the potential caching benefits of Integer.valueOf(int), you could also use this eyesore:

Integer k = Integer.valueOf(Integer.parseInt("123"))

Now, if what you want is the object and not the primitive, then using valueOf(String) may be more attractive than making a new object out of parseInt(String) because the former is consistently present across Integer, Long, Double, etc.

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