Skip to content

Instantly share code, notes, and snippets.

@raghu-icecraft
Created October 24, 2018 02:20
Show Gist options
  • Save raghu-icecraft/8b9d6a68269c89f7a144e8daa3cba86e to your computer and use it in GitHub Desktop.
Save raghu-icecraft/8b9d6a68269c89f7a144e8daa3cba86e to your computer and use it in GitHub Desktop.
In given set of Integers, Find Max sub array and its sum. (Implemented in Java)
/*
Modified Kadane's algortihm
1. http://www.techiedelight.com/maximum-subarray-problem-kadanes-algorithm/
2. compiled and tested using -- https://www.tutorialspoint.com/compile_java_online.php
TODO
a. For all -ves, print the max sub array properly
b. While the output of Max sub array, do the formatting change (extra , at the start)
*/
/* Sample input and output
For input edit integer array of int [] a;
Input and Output:-
1. All -ves not handled well
Input is {-8, -3, -6, -2, -4}
Output:-
Max Sub-array is
Maximum contiguous sum is -2
2. Input is {-2, -3, 4, -1, -2, 1, 5, -3}
Output:-
Max Sub-array is ,4,-1,-2,1,5
Maximum contiguous sum is 7
3. Input is {-2, 3, -1, -4, 4, 3, -1, 2, 3, -4, 1}
Output:-
Max Sub-array is ,4,3,-1,2,3
Maximum contiguous sum is 11
4. Input is {-1, 2, 3, -4, 5, 10}
Output:-
Max Sub-array is ,2,3,-4,5,10
Maximum contiguous sum is 16
5. Input is {0, 1, 3, -1}
Output:-
Max Sub-array is ,0,1,3
Maximum contiguous sum is 4
*/
import java.util.*;
public class MaxSubArrayWithSum{
public static void main (String[] args)
{
//int [] a = {-2, -3, 4, -1, -2, 1, 5, -3};
//int [] a = {-1, 2, 3, -4, 5, 10};
//int [] a = {-2, 3, -1, -4, 4, 3, -1, 2, 3, -4, 1};
//int [] a = {0, 1, 3, -1};
int [] a = {-8, -3, -6, -2, -4};
System.out.println("Maximum contiguous sum is " +
maxSubArray(a));
}
static int maxSubArray(int a[])
{
int size = a.length;
int max_so_far = Integer.MIN_VALUE, max_ending_here = 0;
String result_str = "";
String temp_str = "";
for (int i = 0; i < size; i++)
{
max_ending_here = max_ending_here + a[i];
temp_str = temp_str + "," + a[i];
//test = test + "," + a[i];
if (max_so_far < max_ending_here) {
max_so_far = max_ending_here;
result_str = result_str + temp_str;
temp_str = "";
}
if (max_ending_here < 0) {
max_ending_here = 0;
temp_str = "";
result_str = "";
}
}
System.out.println("Max Sub-array is "+ result_str);
return max_so_far;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment