kadane algo

The Kadane's Algorithm is an efficient way to find the maximum subarray sum in an array of integers. Here is an explanation of each step:

  1. Initialize two variables, "max_so_far" and "max_ending_here," both set to 0. These variables will keep track of the maximum sum seen so far and the maximum sum ending at the current index, respectively.

  2. Iterate through the array from left to right.

  3. At each index, update "max_ending_here" by adding the current element to it. If "max_ending_here" becomes negative, reset it to 0. This is because if the sum of the subarray becomes negative, it is better to start a new subarray from the next index.

  4. Compare "max_so_far" with "max_ending_here" and update "max_so_far" if "max_ending_here" is greater. This step ensures that "max_so_far" always holds the maximum subarray sum seen so far.

  5. Repeat steps 3 and 4 until the end of the array is reached.

  6. After the iteration, "max_so_far" will hold the maximum subarray sum.

Here is an example implementation of the Kadane's Algorithm in C++:

#include <iostream>
#include <climits>

int kadane(int arr[], int size) {
    int max_so_far = INT_MIN;
    int max_ending_here = 0;

    for (int i = 0; i < size; i++) {
        max_ending_here = max_ending_here + arr[i];

        if (max_ending_here < 0)
            max_ending_here = 0;

        if (max_so_far < max_ending_here)
            max_so_far = max_ending_here;
    }

    return max_so_far;
}

int main() {
    int arr[] = {-2, -3, 4, -1, -2, 1, 5, -3};
    int size = sizeof(arr) / sizeof(arr[0]);

    int max_sum = kadane(arr, size);
    std::cout << "Maximum subarray sum: " << max_sum << std::endl;

    return 0;
}

This code will output "Maximum subarray sum: 7", which is the maximum sum of the subarray [4, -1, -2, 1, 5].