Skip to content

Commit 4806283

Browse files
committed
Adding Coding Questions and Solutions - NO NEED TO GET ASSIGNED #150
1 parent 09fcd63 commit 4806283

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Coding/Java/KadanesAlgorithm.java

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
public class KadanesAlgorithm {
2+
public static void main(String[] args) {
3+
// Define an array of integers
4+
int arr[] = {3, -4, 5, 6, -8, 7};
5+
6+
// Call the `kadane` function to find the maximum subarray sum
7+
int maxSubarraySum = kadane(arr);
8+
9+
// Print the result
10+
System.out.println("Maximum Subarray Sum: " + maxSubarraySum);
11+
}
12+
13+
// Kadane's algorithm implementation
14+
static int kadane(int arr[]) {
15+
// Initialize two variables to track the maximum subarray sum ending at the current position (prevmax) and the overall maximum subarray sum (res)
16+
int prevmax = arr[0];
17+
int res = arr[0];
18+
19+
// Iterate through the array starting from the second element (index 1)
20+
for (int i = 1; i < arr.length; i++) {
21+
// Update `prevmax` as the maximum of the current element and the sum of the current element and the previous maximum subarray sum
22+
prevmax = Math.max(arr[i] + prevmax, arr[i]);
23+
24+
// Update `res` as the maximum of `prevmax` and `res`, which represents the overall maximum subarray sum
25+
res = Math.max(prevmax, res);
26+
}
27+
28+
// Return the maximum subarray sum
29+
return res;
30+
}
31+
}

0 commit comments

Comments
 (0)