Write an efficient program to find the sum of contiguous subarray within a one-dimensional array of numbers which has the largest sum.

Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
Java
import java.io.*; // Java program to print largest contiguous array sum import java.util.*; class Kadane { public static void main(String[] args) { int[] a = { -2, -3, 4, -1, -2, 1, 5, -3 }; System.out.println("Maximum contiguous sum is " + maxSubArraySum(a)); } static int maxSubArraySum(int a[]) { int size = a.length; int max_so_far = Integer.MIN_VALUE, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_so_far < max_ending_here) max_so_far = max_ending_here; if (max_ending_here < 0) max_ending_here = 0; } return max_so_far; } } |
chevron_right
filter_none
Output:
Maximum contiguous sum is 7
Above program can be optimized further, if we compare max_so_far with max_ending_here only if max_ending_here is greater than 0.
Java
static int maxSubArraySum(int a[], int size) { int max_so_far = 0, max_ending_here = 0; for (int i = 0; i < size; i++) { max_ending_here = max_ending_here + a[i]; if (max_ending_here < 0) max_ending_here = 0; /* Do not compare for all elements. Compare only when max_ending_here > 0 */ else if (max_so_far < max_ending_here) max_so_far = max_ending_here; } return max_so_far; } // This code is contributed by ANKITRAI1 |
chevron_right
filter_none
Please refer complete article on Largest Sum Contiguous Subarray for more details!
Recommended Posts:
- Java Program for Largest K digit number divisible by X
- Java Program for Find largest prime factor of a number
- Java Program to find largest element in an array
- Java Program To Find Largest Between Three Numbers Using Ternary Operator
- Java Program for Program to calculate area of a Tetrahedron
- Java Program for Program to find area of a circle
- Java Program for Program for array rotation
- Java Program for Range sum queries without updates
- Java Program to find the sum of a Series 1/1! + 2/2! + 3/3! + 4/4! +.......+ n/n!
- Java Program for cube sum of first n natural numbers
- Java Program for Sum of squares of first n natural numbers
- Java Program to Find sum of even factors of a number
- Java Program to Find minimum sum of factors of number
- Java Program for Sum the digits of a given number
- Java Program to find sum of array
- Java Program to Find sum of Series with n-th term as n^2 - (n-1)^2
- Java Program for Subset Sum Problem | DP-25
- Java Program for Maximum sum rectangle in a 2D matrix | DP-27
- Java Program to Display Numbers and Sum of First N Natural Numbers
- Java Program to Calculate Sum of Two Byte Values Using Type Casting

