ProgrammingModerateTCS NQT · Accenture

For an array of 10^6 numbers, which approach finds the largest sum of k consecutive elements fastest and correctly?

  1. A. Recompute each window's sum from scratch, O(n*k)
  2. B. Slide the window by adding the entering value and removing the leaving one, O(n)
  3. C. Sort the array and add the k largest, which ignores adjacency, O(n log n)
  4. D. Try every subset of size k, O(C(n,k))

Correct answer: B. Slide the window by adding the entering value and removing the leaving one, O(n)

A sliding window updates the sum in O(1) per step, so the whole pass is O(n). Sorting ignores the consecutive requirement, so it gives the wrong answer.

More Python Programming questions

Exams that ask this topic