ProgrammingVery hardCompetitive coding (CP)

What is printed?

What is printed?
#include <stdio.h>
int main(void) {
    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 = a[i] > cur + a[i] ? a[i] : cur + a[i];
        if (cur > best) best = cur;
    }
    printf("%d", best);
}
  1. A. 6
  2. B. 12
  3. C. 1
  4. D. 4

Correct answer: A. 6

Kadane keeps the best sum ending at each index (extend the run or restart at a[i]); the best run is 4, -1, 2, 1 = 6. 12 adds every positive element and ignores contiguity, 1 is the whole-array sum, and 4 is the largest single element.

More C Programming questions

Exams that ask this topic