Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Buy and sell a stock any number of times with a one-day cooldown after each sale. Maximise profit.
Problem: Buy and sell a stock any number of times with a one-day cooldown after each sale. Maximise profit.
def cooldown(p):
hold, sold, rest = -p[0], 0, 0
for x in p[1:]:
hold, sold, rest = max(hold, rest - x), hold + x, max(rest, sold)
return max(sold, rest)
print(cooldown([1, 2, 3, 0, 2]), cooldown([1, 2, 4]))What is printed?- A. 4 3
- B. 3 2
- C. 3 3
- D. 2 3
Correct answer: C. 3 3
State machine: hold (own a share), sold (sold today), rest (free to buy). Buy at 1, sell at 2, cool down on 3, buy at 0, sell at 2: 1 + 2 = 3. Without cooldown it would be 2 + 2 = 4. [1, 2, 4] → buy 1, sell 4 = 3. O(n), O(1).
More Coding Interview Problems questions
- Problem: Count the number of distinct ways to reach target t by putting + or − in front of every number. python from functools import…
- Problem: Generate all subsets of a set of feature flags (backtracking) and count those whose sum equals a target. python def count(a, t…
- Problem: Generate all permutations of a list that may contain duplicates, without repeats. How many are produced? python def perms(a)…
- Problem: Generate all valid strings of n pairs of brackets in lexicographic order of the recursion ('(' tried first). python def gen(n)…
- Problem: Count the ways to place n queens on an n × n board so none attack each other. python def queens(n): cols, d1, d2 = set(), set()…
- Problem: Find whether a word exists in a letter grid by moving to adjacent (up/down/left/right) cells without reusing a cell. python def…