Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard
Problem: Trade a stock any number of times (one share at most), but after selling you must wait one day before buying again.
Problem: Trade a stock any number of times (one share at most), but after selling you must wait one day before buying again.
def profit(p):
hold, sold, rest = float('-inf'), 0, 0
for x in p:
hold, sold, rest = max(hold, rest - x), hold + x, max(rest, sold)
return max(sold, rest)
print(profit([3, 1, 4, 8, 2, 5, 9, 1, 6]))What is printed?- A. 19
- B. 12
- C. 14
- D. 11
Correct answer: B. 12
Three states: holding, just sold (cooldown next day) and resting. Unlimited trading without cooldown would collect every rise: 3 + 4 + 3 + 4 + 5 = 19. With the cooldown the best is buy at 1 and sell at 8 (+7), then buy at 1 and sell at 6 (+5) = 12; taking the 2 → 9 rise as well is impossible, and 1→8 plus 5→9 gives only 11.
More Coding Interview Problems questions
- Problem: Wildcard matching where '?' matches one character and '' matches any sequence (including empty); the whole string must match…
- Problem: Count the ways to partition a string into substrings that are all palindromes. python def parts(s): n = len(s); dp = [1] + [0] n…
- Problem: Insert +, − or between the digits of num (or leave digits joined) so that the expression equals target. Count the expressions (no…
- Problem: Check whether a number is a power of four with bit tricks. python def p4(n): return n > 0 and n & (n - 1) == 0 and n & 0x55555555…
- Problem: A number is 'happy' if repeatedly replacing it by the sum of the squares of its digits reaches 1. Cycle detection uses a set…
- Problem: Break n into at least two positive integers to maximise their product. python def brk(n): dp = [0, 1] + [0] (n - 1) for i in…