MCPcopy Create free account
hub / github.com/ashishps1/awesome-leetcode-resources / KadaneAlgorithm

Class KadaneAlgorithm

patterns/java/KadaneAlgorithm.java:3–17  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

1package patterns.java;
2
3public class KadaneAlgorithm {
4 public int maxSubArray(int[] nums) {
5 int currentSum = nums[0]; // Start with the first element
6 int maxSum = nums[0]; // Initialize maxSum with the first element
7
8 // Traverse the array from the second element
9 for (int i = 1; i < nums.length; i++) {
10 // If currentSum is negative, reset to current element
11 currentSum = Math.max(nums[i], currentSum + nums[i]);
12 // Update maxSum if currentSum is greater
13 maxSum = Math.max(maxSum, currentSum);
14 }
15 return maxSum;
16 }
17}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected