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);
}- A. 6
- B. 12
- C. 1
- 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
- How many subarrays of {1, -1, 2, -2, 3} have sum zero? Compute with this program. c #include <stdio.h> int main(void) { int a[] = {1, -1…
- What is printed? c #include <stdio.h> int pc(unsigned n) { return n ? (int)(n & 1u) + pc(n >> 1) : 0; } int main(void) { printf("%d"…
- What is printed? c #include <stdio.h> int main(void) { printf("%d", (13 << 1) + 13); }
- How many numbers from 1 to 100 are multiples of 16? Compute with this program. c #include <stdio.h> int main(void) { int c = 0; for…
- What is printed? c #include <stdio.h> int main(void) { unsigned x = 1u << 31; x <<= 1; printf("%u", x); }
- What is printed? c #include <stdio.h> int main(void) { printf("%d", 'n' == 10 && '0' == 0); }