Find the maximum sum of subarray with Kadane's algorithm
//test case
int maxKanade, startKanade, endKanade;
maxKanade = Kadane(new List<int>() { 2, -4, 6, -3, 9 }, out startKanade, out endKanade);
Debug.WriteLine("{0} {1} {2}", maxKanade, startKanade, endKanade);
maxKanade = Kadane(new List<int>() { 3, 4, 6, -3, -9 }, out startKanade, out endKanade);
Debug.WriteLine("{0} {1} {2}", maxKanade, startKanade, endKanade);
//test case end
public static int Kadane(List<int> input, out int start, out int end)
{
//from wiki https://en.wikipedia.org/wiki/Maximum_subarray_problem
//def max_subarray(A):
//max_ending_here = max_so_far = 0
//for x in A:
// max_ending_here = max(0, max_ending_here + x)
// max_so_far = max(max_so_far, max_ending_here)
//return max_so_far
start = 0;
int s = 0;
end = 0;
int count = 0;
int max_ending_here = 0, max_so_far = 0;
foreach(int i in input)
{
if (max_ending_here + i > 0)
{
max_ending_here += i;
}
else
{
// if go negative basically take a fresh start
max_ending_here = 0;
s = count + 1;
}
if (max_so_far < max_ending_here)
{
max_so_far = max_ending_here;
end = count;
start = s;
}
count++;
}
return max_so_far;
}
Kanade()defined? \$\endgroup\$Sorry I had a misspell-had?int maxKanade, startKanade, endKanade;and uses thereof. (Then,misspellis no noun in my book.) \$\endgroup\$