Please note, this is a STATIC archive of website www.w3resource.com from 19 Jul 2022, cach3.com does not collect or store any user information, there is no "phishing" involved.
w3resource

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

Java Basic: Exercise-123 with Solution

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) {
     ArrayList<Integer> nums = new ArrayList<Integer>();
      nums.add(-2);
      nums.add(1);
      nums.add(-3);
      nums.add(4);
      System.out.print(min_SubArray(nums)); 
}
 public static int min_SubArray(ArrayList<Integer> nums) { 
   int[] nums1 = new int[nums.size()];
        nums1[0] = nums.get(0);
        int min = nums1[0];
        for (int i = 1; i < nums.size(); ++i) {
            nums1[i] = Math.min(nums.get(i), nums.get(i) + nums1[i - 1]);
            min = Math.min(min, nums1[i]);
        }
        return min;
 }
}

Sample Output:

-4 

Flowchart:

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

Java Code Editor:

Contribute your code and comments through Disqus.

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.



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