ProgrammingHardProduct company OA · GATE CS

What is printed?

What is printed?
int a[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};
int best = a[0], cur = a[0];
for (int i = 1; i < 9; i++) {
    cur = cur + a[i] > a[i] ? cur + a[i] : a[i];
    if (cur > best) best = cur;
}
printf("%d", best);
  1. A. 4
  2. B. 7
  3. C. 1
  4. D. 6

Correct answer: D. 6

This is Kadane's algorithm: cur is the best sum of a run ending at i, restarting whenever the old run would only drag a[i] down. The best run is 4, −1, 2, 1 = 6. '7' adds the final 4 across the −5; '1' is the total of the whole array.

More C Programming questions

Exams that ask this topic