Skip to content

Commit 59f394d

Browse files
authored
Merge pull request #6 from Nikzy7/kadane
Added Kadane's Algorithm
2 parents ec7c459 + dd6bfa5 commit 59f394d

File tree

1 file changed

+54
-0
lines changed

1 file changed

+54
-0
lines changed

kadane.java

+54
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
/*
2+
3+
Kadane's Algorithm:
4+
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.
5+
This is one of the most popular problems and is asked in almost all of the Technical Interviews of top Companies.
6+
Kadne's algorithm can be used to find the sum of the largest sum contiguous subarray or modified to find the subarray itself.
7+
8+
Contributor's Note:
9+
This is a pretty easy algorithm to understand, although, seems a little scary by its name. I faced this problem in the interviews of companies like Walmart and Amazon.
10+
11+
For a Video based Explanation, check out my favorite video on this topic:
12+
https://youtu.be/jnoVtCKECmQ
13+
14+
*/
15+
16+
import java.util.*;
17+
18+
class kadane{
19+
public static void main(String[] args)
20+
{
21+
Scanner s = new Scanner(System.in);
22+
23+
System.out.print("Enter Size of Array :");
24+
int arr_size = s.nextInt();
25+
26+
int[] arr = new int[arr_size];
27+
28+
int i;
29+
30+
System.out.println("Enter Elements : ");
31+
32+
for(i=0;i<arr_size;i++)
33+
arr[i] = s.nextInt();
34+
35+
System.out.print("The maximum contiguous subarray sum is : ");
36+
System.out.print(kadane_func(arr));
37+
s.close();
38+
}
39+
40+
//function implementing kadane's algo
41+
static int kadane_func(int[] arr)
42+
{
43+
int max_val = arr[0];
44+
int current = max_val;
45+
46+
for(int i=1;i<arr.length;i++)
47+
{
48+
current = Math.max(arr[i]+current,arr[i]);
49+
max_val = Math.max(current,max_val);
50+
}
51+
52+
return max_val;
53+
}
54+
}

0 commit comments

Comments
 (0)