ProgrammingVery hardProduct company OA

What is printed?

What is printed?
int a[] = {2, 1, 3, 2, 4, 1}, best = 0, s = 0, lo = 0;
for (int hi = 0; hi < 6; hi++) {
    s += a[hi];
    while (s > 6) s -= a[lo++];
    if (hi - lo + 1 > best) best = hi - lo + 1;
}
printf("%d", best);
  1. A. 4
  2. B. 2
  3. C. 3
  4. D. 6

Correct answer: C. 3

This sliding window finds the longest run of consecutive elements with sum at most 6. Windows 2 1 3 and 1 3 2 both sum to 6 with length 3; any 4 consecutive elements sum to at least 8. '6' ignores the limit.

More C Programming questions

Exams that ask this topic