w3resource

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

Java Basic: Exercise-123 with Solution

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.

Java Code Editor:

Previous: Write a Java program to find a contiguous subarray with largest sum from a given array of integers.
Next: Write a Java program to find the index of a value in a sorted array. If the value does not find return the index where it would be if it were inserted in order.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/java-exercises/basic/java-basic-exercise-123.php