File tree Expand file tree Collapse file tree 1 file changed +55
-0
lines changed
Expand file tree Collapse file tree 1 file changed +55
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments