Java: Find contiguous subarray within a given array of integers which has the largest sum
66. Find subarray with largest sum in a given array
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:
Sample Output:
Original array: [1, 2, -3, -4, 0, 6, 7, 8, 9] The largest sum of contiguous sub-array: 30
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program to find the largest sum of a non-contiguous subarray.
- Write a Java program to find the maximum sum of a subarray containing at least one negative number.
- Write a Java program to find the subarray with the largest sum that contains at least one odd number.
- Write a Java program to find the longest contiguous subarray whose sum is greater than a given value.
Go to:
PREV : Find maximum difference between two elements in an array.
NEXT : Find subarray with largest sum in a circular array.
Java Code Editor:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.