Maximum Sum SubArray

You can replace Math.Max functions by if statements and update start and end index of the best subarray. Pascal version:

    if X[i] > sum + X[i] then begin
        sum := X[i];
        start := i;
      end
      else
        sum := sum + X[i];
      if max < sum then begin
        max := sum;
        finish := i;
      end;

You can track the starting and ending indexes of the current best subarray in your loop. Instead of using max() to compute sumand max, just do the following :

int sum_start = 0, sum_end = 0, start = 0, end = 0;
// In the for loop
if (X[i] > sum + X[i]) {
    sum = X[i];
    sum_start = i;
    sum_end = i;
} else {
    ++sum_end;
}
if (sum > max) {
    start = sum_start;
    end = sum_end;
    max = sum;
}

there is an o(n) solution, a single for loop through the array and reset your sub-sequence whenever your current total is below 0.

{5, 15, -30, 10, -5, 40, 10}

  • 5 + 15 = 20
  • 20 - 30 = -10 (reset sub-sequence)
  • 10 -5 +40 +10 = 55
  • end. 55 is max sub-sequence

edit: to get subsequence... whenever you change max, update your subsequence

  • current left index changes only when u reset
  • current right index changes every iteration
  • new max -> save current left and right index...