-
Notifications
You must be signed in to change notification settings - Fork 7.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #473 from sudipbhakat07/master
Added Kadane's Algorithm Problem
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
55 changes: 55 additions & 0 deletions
55
Program's_Contributed_By_Contributors/Java_Programs/Kadane.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
import java.io.*; | ||
|
||
public class Kadane { | ||
|
||
public static void main (String[] args) throws IOException { | ||
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); | ||
//size of array | ||
int n = Integer.parseInt(br.readLine().trim()); | ||
int arr[] = new int[n]; | ||
String inputLine[] = br.readLine().trim().split(" "); | ||
|
||
//adding elements | ||
for(int i=0; i<n; i++){ | ||
arr[i] = Integer.parseInt(inputLine[i]); | ||
} | ||
|
||
Kadane obj = new Kadane(); | ||
|
||
//calling maxSubarraySum() function | ||
System.out.println(obj.maxSubarraySum(arr, n)); | ||
} | ||
|
||
// Function to find subarray with maximum sum | ||
int maxSubarraySum(int arr[], int n) { | ||
if(n==0) | ||
return 0; | ||
int max_ending_here = 0, max_so_far = arr[0]; | ||
|
||
for(int i=0;i<n;i++) { | ||
max_ending_here += arr[i]; | ||
if(max_ending_here < 0) | ||
max_ending_here = 0; | ||
else if(max_so_far <= max_ending_here) { | ||
max_so_far = max_ending_here; | ||
} | ||
} | ||
return max_so_far; | ||
} | ||
} | ||
|
||
|
||
|
||
|
||
|
||
/** | ||
Input: | ||
5 | ||
1 2 3 -2 5 | ||
Output: | ||
9 | ||
Explanation: | ||
Max subarray sum is 9 | ||
of elements (1, 2, 3, -2, 5) which | ||
is a contiguous subarray. | ||
*/ |