ProgrammingModerateTCS NQT · Accenture
For an array of 10^6 numbers, which approach finds the largest sum of k consecutive elements fastest and correctly?
- A. Recompute each window's sum from scratch, O(n*k)
- B. Slide the window by adding the entering value and removing the leaving one, O(n)
- C. Sort the array and add the k largest, which ignores adjacency, O(n log n)
- 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
- Which statement about the bisect module is FALSE?
- What is printed? python def mink(piles, h): lo, hi = 1, max(piles) while lo < hi: mid = (lo + hi) // 2 if sum(-(-p // mid) for p in piles)…
- What is printed? python import heapq def huff(freqs): h = list(freqs) heapq.heapify(h) cost = 0 while len(h) > 1: a = heapq.heappop(h) b =…
- What is printed? python def zeros(n): c = 0 while n: n //= 5 c += n return c print(zeros(100), zeros(25))
- What is printed? python def mincut(s): n = len(s) pal = [[False] n for in range(n)] for i in range(n - 1, -1, -1): for j in range(i, n)…
- What is printed? python def triecount(words, pref): root = {} for w in words: node = root for ch in w: node = node.setdefault(ch, {})…