Data Structures & AlgorithmsModerateCodeforces Div2 C/D · Amazon SDE OA

Count the subarrays of w = [1, 3, 2, 5, 4, 4, 2] whose maximum minus minimum is at most 3. Run the brute-force count.

Count the subarrays of w = [1, 3, 2, 5, 4, 4, 2] whose maximum minus minimum is at most 3. Run the brute-force count.
w=[1,3,2,5,4,4,2]
print(sum(1 for i in range(len(w)) for j in range(i,len(w)) if max(w[i:j+1])-min(w[i:j+1])<=3))
What is printed?
  1. A. 11
  2. B. 24
  3. C. 15
  4. D. 17

Correct answer: B. 24

Each subarray is checked directly, including length-one subarrays. A tighter bound (at most 1 or at most 2) undercounts, and skipping single elements drops valid subarrays.

More Coding Interview Problems questions

Exams that ask this topic