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:
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.
Java: Tips of the Day
How to sort an ArrayList?
Collections.sort(testList); Collections.reverse(testList);
That will do what you want. Remember to import Collections though!
Ref: https://bit.ly/32urdSe
- New Content published on w3resource:
- HTML-CSS Practical: Exercises, Practice, Solution
- Java Regular Expression: Exercises, Practice, Solution
- Scala Programming Exercises, Practice, Solution
- Python Itertools exercises
- Python Numpy exercises
- Python GeoPy Package exercises
- Python Pandas exercises
- Python nltk exercises
- Python BeautifulSoup exercises
- Form Template
- Composer - PHP Package Manager
- PHPUnit - PHP Testing
- Laravel - PHP Framework
- Angular - JavaScript Framework
- Vue - JavaScript Framework
- Jest - JavaScript Testing Framework