Data Structures & AlgorithmsEasyAccenture · Cognizant coding round pattern

Problem: A stock tracker gets daily prices and must report the best profit from one buy followed by one later sell (0 if no profit is possible). Example: [7, 1, 5, 3, 6, 4] → 5.

Problem: A stock tracker gets daily prices and must report the best profit from one buy followed by one later sell (0 if no profit is possible). Example: [7, 1, 5, 3, 6, 4] → 5.
def best(p):
    lo, ans = p[0], 0
    for x in p[1:]:
        ans = max(ans, x - lo)
        lo = min(lo, x)
    return ans
print(best([9, 4, 6, 2, 5, 3, 8]))
What is printed?
  1. A. 4
  2. B. 6
  3. C. 7
  4. D. 2

Correct answer: B. 6

Track the cheapest price seen so far and the best difference. The minimum drops to 2 on day 4 and the later price 8 gives 8 − 2 = 6. Taking max − min over the whole array (9 − 2 = 7) ignores that the sell must come after the buy. O(n) time, O(1) space.

More Coding Interview Problems questions

Exams that ask this topic