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);- A. 4
- B. 7
- C. 1
- 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
- What is printed? c int a[] = {2, 4, 6, 8, 10, 12, 14}, lo = 0, hi = 6, steps = 0, x = 7; while (lo <= hi) { int m = (lo + hi) / 2…
- What is printed? c struct E { char n; int age; } e[] = {{'A', 30}, {'B', 25}, {'C', 35}}; int cmp(const void x, const void y) { return…
- What is printed? c #define SCALE(x) (x factor) int factor = 3; int f(void) { int factor = 10; return SCALE(2); } int main(void) {…
- What is printed? c int i = 0, n = 0; while (i++, i < 4) n += i; printf("%d %d", n, i);
- What is the range of values of a signed 8-bit two's-complement integer?
- What is printed? c unsigned x = 8; if (x & (x - 1) == 0) puts("pow2"); else puts("not");