Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA
Problem: Trade a stock any number of times (hold at most one share); each completed sale pays a fixed fee. Maximise profit with two states: holding and not holding.
Problem: Trade a stock any number of times (hold at most one share); each completed sale pays a fixed fee. Maximise profit with two states: holding and not holding.
def profit_fee(prices, fee):
hold, cash = -prices[0], 0
for p in prices[1:]:
hold, cash = max(hold, cash - p), max(cash, hold + p - fee)
return cash
pr = [2, 7, 5, 9, 3, 8]
print(profit_fee(pr, 2), profit_fee(pr, 4))What is printed?- A. 9 4
- B. 8 6
- C. 12 4
- D. 8 4
Correct answer: D. 8 4
hold = best value while owning a share, cash = best value with none. With fee 2: e.g. buy 2 / sell 9 (+5) then buy 3 / sell 8 (+3) → 8; trading every rise (+5, +4, +5 = 14 gross) pays three fees → 8 as well. With fee 4 only big swings pay: 2 → 9 (+3) and 3 → 8 (+1) → 4. Ignoring the fee gives 12 for the two swings. O(n), O(1).
More Coding Interview Problems questions
- Problem: Is c formed by interleaving a and b (keeping each string's internal order)? dp[i][j] = first i chars of a and j chars of b can…
- Problem: Wildcard matching over the whole string: '?' matches any one character, '' matches any sequence (including empty). python def…
- Problem: Return (length of the longest strictly increasing subsequence, number of such longest subsequences). python def numlis(a): n =…
- Problem: With k identical eggs and an n-floor building, find the minimum number of drops that guarantees finding the critical floor. DP on…
- Problem: Two players alternately take a pile from either END of a row; both play optimally. Compute (first player's total − second…
- Problem: Maximum sum of a non-empty contiguous subarray where you may delete at most one element (the result must stay non-empty). Track…