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?- A. 4
- B. 6
- C. 7
- 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
- Problem: Find the largest sum of a non-empty contiguous block of an array (values may be negative). python def best(a): cur = ans = a[0]…
- Problem: Rotate an array to the right by k steps in place, using O(1) extra space. Example: [1, 2, 3, 4, 5], k = 2 → [4, 5, 1, 2, 3]…
- Problem: Every number in a list of sensor IDs appears twice except one. Find the lonely ID in O(n) time and O(1) space. python def…
- Problem: Return, for every index i, the product of all elements except a[i], without using division. Example: [1, 2, 3, 4] → [24, 12, 8…
- Problem: Given an array where values lie in 1..n, find the value that appears twice (exactly one does) without modifying the array. python…
- Problem: Given n ≤ 10⁵ integers (not sorted), find the length of the longest run of consecutive values, e.g. [100, 4, 200, 1, 3, 2] → 4…