Skip to content

Commit 16ca13a

Browse files
committed
#HactoberFest2024
1 parent 8d57707 commit 16ca13a

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Subproject commit 4a2bd71026da43e433d8759b1b47c1c1f78e7dc0

kadanesAlgorithm.java

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import java.util.Scanner;
2+
3+
class KadanesAlgorithm {
4+
public static void main(String[] args) {
5+
Scanner sc = new Scanner(System.in);
6+
System.out.println("Enter the size of the array:");
7+
int n = sc.nextInt();
8+
9+
int[] arr = new int[n];
10+
System.out.println("Enter the elements of the array:");
11+
for (int i = 0; i < n; i++) {
12+
arr[i] = sc.nextInt();
13+
}
14+
15+
int maxSum = kadanesAlgorithm(arr);
16+
System.out.println("The maximum sum of a contiguous subarray is: " + maxSum);
17+
sc.close();
18+
}
19+
20+
public static int kadanesAlgorithm(int[] arr) {
21+
int maxCurrent = arr[0];
22+
int maxGlobal = arr[0];
23+
24+
for (int i = 1; i < arr.length; i++) {
25+
maxCurrent = Math.max(arr[i], maxCurrent + arr[i]);
26+
if (maxCurrent > maxGlobal) {
27+
maxGlobal = maxCurrent;
28+
}
29+
}
30+
31+
return maxGlobal;
32+
}
33+
}

0 commit comments

Comments
 (0)