﻿ Java exercises: Find minimum subarray sum of specified size in a given array of integers - 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;

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 = last - k + 1;
result = last;
result = 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, result, result);
}
}
```
```

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: Java Code Editor:

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

﻿

## Java: Tips of the Day

Array vs ArrayLists:

The main difference between these two is that an Array is of fixed size so once you have created an Array you cannot change it but the ArrayList is not of fixed size. You can create instances of ArrayLists without specifying its size. So if you create such instances of an ArrayList without specifying its size Java will create an instance of an ArrayList of default size.

Once an ArrayList is full it re-sizes itself. In fact, an ArrayList is internally supported by an array. So when an ArrayList is resized it will slow down its performance a bit as the contents of the old Array must be copied to a new Array.

At the same time, it's compulsory to specify the size of an Array directly or indirectly while creating it. And also Arrays can store both primitives and objects while ArrayLists only can store objects.

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