Kadane's Algorithm

Kadane's Algorithm

  1. Kadane's Algorithm Explained:

    Kadane’s Algorithm is a famous method used to solve the Maximum Subarray Sum problem efficiently. The goal is to find the contiguous subarray in a given array that has the largest sum.

    How It Works:

    1. Iterate Through the Array: Traverse the array, considering each element as part of a subarray.

    2. Keep Track of Two Variables:

      • currentSum: The sum of the current subarray being evaluated.

      • maxSum: The maximum sum encountered so far.

    3. Decision at Each Step: For each element, decide:

      • Should the current element be added to the existing subarray (currentSum + arr[i])?

      • Or should a new subarray start from this element (arr[i])?

      • Take the maximum of these two options.

    4. Update Maximum Sum: If the currentSum exceeds maxSum, update maxSum.

    5. End Result: At the end of the iteration, maxSum contains the largest sum of a contiguous subarray.


Algorithm:

  1. Initialize:

    • currentSum = 0

    • maxSum = Integer.MIN_VALUE (or a very small value to handle negative arrays).

  2. Iterate through the array:

    • Update currentSum = max(arr[i], currentSum + arr[i]).

    • Update maxSum = max(maxSum, currentSum).

  3. Return maxSum.


Example Walkthrough:

Input:

arr = [-2, 1, -3, 4, -1, 2, 1, -5, 4]

Steps:

IndexCurrent ElementcurrentSum CalculationmaxSum Update
0-2currentSum = max(-2, 0 + (-2)) = -2maxSum = max(-∞, -2) = -2
11currentSum = max(1, -2 + 1) = 1maxSum = max(-2, 1) = 1
2-3currentSum = max(-3, 1 + (-3)) = -2maxSum = max(1, -2) = 1
34currentSum = max(4, -2 + 4) = 4maxSum = max(1, 4) = 4
4-1currentSum = max(-1, 4 + (-1)) = 3maxSum = max(4, 3) = 4
52currentSum = max(2, 3 + 2) = 5maxSum = max(4, 5) = 5
61currentSum = max(1, 5 + 1) = 6maxSum = max(5, 6) = 6
7-5currentSum = max(-5, 6 + (-5)) = 1maxSum = max(6, 1) = 6
84currentSum = max(4, 1 + 4) = 5maxSum = max(6, 5) = 6

Output:

maxSum = 6


Advantages:

  1. Time Complexity:

    • O(n): Only one traversal of the array is required.
  2. Space Complexity:

    • O(1): No additional data structures are used, just two variables.

Edge Cases:

  1. All Negative Numbers:

    • Input: arr = [-3, -5, -1, -2]

    • Output: -1 (The maximum subarray is the single largest element, -1).

  2. Single Element Array:

    • Input: arr = [5]

    • Output: 5.

  3. All Positive Numbers:

    • Input: arr = [1, 2, 3, 4]

    • Output: 10 (The entire array is the subarray).


Code Example in Java:

    public class KadaneAlgorithm {
        public static int maxSubArraySum(int[] arr) {
            int currentSum = 0;
            int maxSum = Integer.MIN_VALUE;

            for (int num : arr) {
                currentSum = Math.max(num, currentSum + num);
                maxSum = Math.max(maxSum, currentSum);
            }

            return maxSum;
        }

        public static void main(String[] args) {
            int[] arr = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
            System.out.println("Maximum Subarray Sum: " + maxSubArraySum(arr));
        }
    }

Real-Life Applications:

  1. Financial Analysis:

    • Identify the period with the highest profit in stock prices.
  2. Signal Processing:

    • Detect the strongest signal in a noisy dataset.
  3. Gaming:

    • Find the maximum score achievable in a segment of a game.