Skip to content

Commit 516f65e

Browse files
authored
Merge pull request TheAlgorithms#344 from NISHITA97/Branch2
Kadane's Algorithm added
2 parents 6efaddb + 9dc1ac2 commit 516f65e

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import java.util.Scanner;
2+
3+
/**
4+
* Program to implement Kadane’s Algorithm to
5+
* calculate maximum contiguous subarray sum of an array
6+
* Time Complexity: O(n)
7+
*
8+
* @author Nishita Aggarwal
9+
*
10+
*/
11+
12+
public class KadaneAlgorithm {
13+
14+
/**
15+
* This method implements Kadane's Algorithm
16+
*
17+
* @param arr The input array
18+
* @return The maximum contiguous subarray sum of the array
19+
*
20+
*/
21+
static int largestContiguousSum(int arr[]){
22+
int i,len=arr.length,cursum=0,maxsum=Integer.MIN_VALUE;
23+
if(len==0) //empty array
24+
return 0;
25+
for(i=0;i<len;i++){
26+
cursum+=arr[i];
27+
if(cursum>maxsum){
28+
maxsum=cursum;
29+
}
30+
if(cursum<=0){
31+
cursum=0;
32+
}
33+
}
34+
return maxsum;
35+
}
36+
37+
/**
38+
* Main method
39+
*
40+
* @param args Command line arguments
41+
*/
42+
public static void main(String[] args) {
43+
Scanner sc=new Scanner(System.in);
44+
int n,arr[],i;
45+
n=sc.nextInt();
46+
arr=new int[n];
47+
for(i=0;i<n;i++){
48+
arr[i]=sc.nextInt();
49+
}
50+
int maxContSum=largestContiguousSum(arr);
51+
System.out.println(maxContSum);
52+
sc.close();
53+
}
54+
55+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy