Java: Find contiguous subarray within a given array of integers which has the largest sum
Java Array: Exercise-66 with Solution
Write a Java program to find a contiguous subarray within a given array of integers with the largest sum.
In computer science, the maximum sum subarray problem is the task of finding a contiguous subarray with the largest sum, within a given one-dimensional array A[1...n] of numbers. Formally, the task is to find indices and with, such that the sum is as large as possible.
Example:
Input :
int[] A = {1, 2, -3, -4, 0, 6, 7, 8, 9}
Output:
The largest sum of contiguous sub-array: 30
Sample Solution:
Java Code:
// Import the necessary Java class.
import java.util.Arrays;
// Define a class named 'solution'.
class solution {
// Method to find the largest sum of a contiguous sub-array.
public static int largest_sum(int[] A) {
// Initialize variables for maximum element value and maximum ending here.
int max_ele_val = 0;
int max_end = 0;
// Iterate through the elements in array 'A'.
for (int i : A) {
max_end = max_end + i;
// Ensure that 'max_end' doesn't go below zero.
max_end = Integer.max(max_end, 0);
// Update 'max_ele_val' with the maximum value.
max_ele_val = Integer.max(max_ele_val, max_end);
}
return max_ele_val;
}
// Main method to demonstrate finding the largest sum of a contiguous sub-array.
public static void main(String[] args) {
// Initialize an array.
int[] A = {1, 2, -3, -4, 0, 6, 7, 8, 9};
System.out.println("\nOriginal array: " + Arrays.toString(A));
// Call the 'largest_sum' method to find and print the largest sum.
System.out.println("The largest sum of a contiguous sub-array: " + largest_sum(A));
}
}
Sample Output:
Original array: [1, 2, -3, -4, 0, 6, 7, 8, 9] The largest sum of contiguous sub-array: 30
Flowchart:
Java Code Editor:
Previous: Write a Java program to find maximum difference between two elements in a given array of integers such that smaller element appears before larger element.
Next: Write a Java program to find subarray which has the largest sum in a given circular array of integers.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
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://w3resource.com/java-exercises/array/java-array-exercise-66.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics