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:
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:
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
- 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