ProgrammingVery hardTCS NQT · Accenture

An array holds the values [3, 0, 2, 0, 1] (positions 0 to 4). The procedure below computes the water trapped above each position as min(leftmax, rightmax) - height, when that is positive, and prints the total. What is printed?

An array holds the values [3, 0, 2, 0, 1] (positions 0 to 4). The procedure below computes the water trapped above each position as min(leftmax, rightmax) - height, when that is positive, and prints the total. What is printed?
leftmax[i] = max of a[0..i]; rightmax[i] = max of a[i..n-1]
total = sum over i of max(0, min(leftmax[i], rightmax[i]) - a[i])
Print total
  1. A. 2
  2. B. 3
  3. C. 9
  4. D. 6

Correct answer: B. 3

Water sits above index 1 (min(3,2) - 0 = 2) and above index 3 (min(2,1) - 0 = 1), so the trapped total is 3. Counting the positions with water gives 2, using the larger side gives 9, and the sum of the heights is 6.

More Pseudocode and Code Tracing questions

Exams that ask this topic