Kadane's algorithm is used to find the maximum contiguous sum in an array. A contiguous sum is the sum of a contiguous subarray of a given array. For example, in the array [1, 2, -3, 4, 5, -1, 2]
, the contiguous sums are 1
, 3
, 0
, 4
, 9
, 8
, 10
, 3
, and 5
. The maximum contiguous sum is 10
, which is the sum of the subarray [4, 5, -1, 2]
.
Kadane's algorithm can be used to solve various problems that involve finding the maximum contiguous sum in an array, such as,
- Finding the maximum subarray sum in an array of integers
- Finding the maximum sum of a submatrix in a matrix of integers
- Finding the maximum sum of a contiguous subsequence in a sequence of integers
To use Kadane's algorithm, you simply need to pass the array (or matrix or sequence) to the Kadane function and it will return the maximum contiguous sum.
Here is an example of how you might use Kadane's algorithm to find the maximum contiguous sum in an array of integers,
using System;
namespace Kadane {
class Program {
static void Main(string[] args) {
// Test the Kadane function with an example array
int[] arr = {
-2,
1,
-3,
4,
-1,
2,
1,
-5,
4
};
int maxSum = Kadane(arr);
Console.WriteLine("Maximum contiguous sum is " + maxSum);
}
static int Kadane(int[] arr) {
// Initialize maximum sum and current sum to the first element of the array
int maxSum = arr[0];
int currSum = arr[0];
// Loop through the rest of the array
for (int i = 1; i < arr.Length; i++) {
// Update the current sum by taking the maximum of the current element and the current element plus the current sum
currSum = Math.Max(arr[i], currSum + arr[i]);
// Update the maximum sum by taking the maximum of the current sum and the maximum sum
maxSum = Math.Max(maxSum, currSum);
}
return maxSum;
}
}
}
Kadane's algorithm is an efficient algorithm for finding the maximum contiguous sum in an array. It works by iterating through the array and maintaining two variables: maxSum
and currSum
. maxSum
stores the maximum contiguous sum found so far, and currSum
stores the current contiguous sum. At each iteration, currSum
is updated by taking the maximum of the current element and the current element plus the current sum. Then, maxSum
is updated by taking the maximum of the current sum and the maximum sum. This process continues until the end of the array is reached, at which point maxSum
will contain the maximum contiguous sum.