Skip to content

Instantly share code, notes, and snippets.

@aliprogrammer69
Last active August 6, 2022 10:08
Show Gist options
  • Select an option

  • Save aliprogrammer69/c700ceddb20f04de9c6db6ef9d5bae6f to your computer and use it in GitHub Desktop.

Select an option

Save aliprogrammer69/c700ceddb20f04de9c6db6ef9d5bae6f to your computer and use it in GitHub Desktop.
best practice for the kadane's algorithm
public static (int, int) Calculate(int[] array) {
if (array.Length == 0)
return (0, 0);
int firstIndex = 0, lastIndex = 0, candidateFirstIndex = 0;
int currectSum = 0;
int globalSum = array[0];
for (int i = 0; i < array.Length; i++) {
currectSum += array[i];
if (array[i] >= currectSum) {
candidateFirstIndex = i;
currectSum = array[i];
}
if (currectSum > globalSum) {
lastIndex = i;
firstIndex = candidateFirstIndex;
globalSum = currectSum;
}
}
return (firstIndex, lastIndex);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment