Data Structures & AlgorithmsHardGATE CS · TCS NQT · Product Company SDE

What does this code compute, and what is its time complexity for an array of n elements?

What does this code compute, and what is its time complexity for an array of n elements?
int best = a[0];
for (int i = 1; i < n; i++)
  if (a[i] > best) best = a[i];
  1. A. The minimum, in O(log n)
  2. B. The maximum, in O(n)
  3. C. The maximum, in O(n^2)
  4. D. The sum, in O(n)

Correct answer: B. The maximum, in O(n)

A single pass keeps the largest value seen so far, which finds the maximum in one linear scan, O(n).

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

Exams that ask this topic