GATE Computer ScienceVery hardGATE CS (PYQ pattern)

int a[] = {5, 3, 8, 4, 2, 9, 1, 7, 6, 10}; int st[10], top = -1, nge[10]; for (int i = 0; i < 10; i++) nge[i] = -1; for (int i = 0; i < 10; i++) { while (top >= 0 && a[st[top]] < a[i]) nge[st[top--]] = a[i]; st[++top] = i; } What is the sum of nge[0..9], and how many elements remain on the stack at the end?

  1. A. 79 and 1
  2. B. 80 and 1
  3. C. 79 and 2
  4. D. 74 and 0

Correct answer: A. 79 and 1

nge = [8, 8, 9, 9, 9, 10, 7, 10, 10, -1] (the last stack elements keep -1), so the sum is 79; the stack ends holding only the final maximum.

More Programming and Data Structures (GATE) questions

Exams that ask this topic