w3resource

Java: Find the subarray with smallest sum from a given array of integers.


Min Subarray Sum

Write a Java program to find the subarray with smallest sum from a given array of integers.

Pictorial Presentation:

Java Basic Exercises: Find the subarray with smallest sum from a given array of integers.


Sample Solution:

Java Code:

import java.util.*;

public class Main {
    public static void main(String[] args) {
        // Create an ArrayList to store integers
        ArrayList nums = new ArrayList();
        nums.add(-2);
        nums.add(1);
        nums.add(-3);
        nums.add(4);
        // Call the min_SubArray function and print the result
        System.out.print(min_SubArray(nums)); 
    }

    public static int min_SubArray(ArrayList nums) { 
        // Create an array to store the same integers for dynamic programming
        int[] nums1 = new int[nums.size()];
        nums1[0] = nums.get(0);
        // Initialize the minimum value to the first element
        int min = nums1[0];
        // Loop through the ArrayList to calculate minimum subarray sum
        for (int i = 1; i < nums.size(); ++i) {
            // Calculate the minimum of the current element and the sum of the previous subarray
            nums1[i] = Math.min(nums.get(i), nums.get(i) + nums1[i - 1]);
            // Update the minimum value if needed
            min = Math.min(min, nums1[i]);
        }
        // Return the minimum subarray sum
        return min;
    }
}

Sample Output:

-4 

Flowchart:

Flowchart: Java exercises: Find the subarray with smallest sum from a given array of integers.


For more Practice: Solve these Related Problems:

  • Modify the program to find the smallest sum of a subarray with at least k elements.
  • Write a program to find the minimum subarray sum using a prefix sum array.
  • Modify the program to find the smallest sum of a circular subarray.
  • Write a program to find the smallest sum subarray with a given sum target.

Go to:


PREV : Max Subarray Sum.
NEXT : Insert Index in Sorted Array.


Java Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.