Data Structures & AlgorithmsVery hardGATE CS

For each index i of [4, 7, 3, 8, 2, 2, 9, 1, 6, 5, 10, 3], let g(i) be the index of the first element to the right that is strictly greater than a[i] (and g(i) = i if none exists). What is the sum of (g(i) - i) over all i?

  1. A. 22
  2. B. 86
  3. C. 18
  4. D. 15

Correct answer: C. 18

Using a monotonic stack the next-greater indices give distances whose total is 18. The sum of the next greater values is 86, a different quantity.

More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions

Exams that ask this topic