Worst Equity Drop, Best Trade, and Fewest Coins
Dynamic ProgrammingAuto-graded · 22 test casesLast updated
Return a series' steepest peak-to-trough drop with its indices, the best one-buy-one-sell gain, and the minimum coin count for a target.
You receive four arguments: a cumulative profit-and-loss series pnl, a list of daily share prices prices, a list of coin denominations coins, and a non-negative target amount. Produce three results and return them together in one dictionary whose keys are "drawdown", "profit", and "coins".
1. Steepest drop of the cumulative series ("drawdown")
A drop is anchored at an index p (a peak) and closed at a later-or-equal index t (a trough), with p <= t. Its size is pnl[t] - pnl[p], which is at most zero. Report the most negative value this expression takes over all valid p <= t.
The value under "drawdown" is a list [size, start, end] where:
sizeis that most negative value, or0when no pair yields a negative value;startisp + 1, i.e. the index directly following the peakpbehind the steepest drop;endist, the trough index.
Tie-breaking: when several pairs share the same steepest size, keep the pair whose trough t comes first — scan left to right and overwrite only on a strictly smaller size. Likewise, when raising the running peak, only accept a strictly greater value, so the earliest of several equal peaks stays the reference. If the steepest size is 0 (including when pnl is empty), return [0, -1, -1].
2. Best single trade ("profit")
Pick a buy day j and a sell day i with j < i; the gain is prices[i] - prices[j]. Return the largest such gain as a non-negative integer, and 0 when no profitable trade is possible (also when there are fewer than two days).
3. Fewest coins for the target ("coins")
Every denomination in coins may be reused without limit. Return the smallest number of coins whose values add up to exactly amount, or -1 when no combination does (also when coins holds no positive denomination). Denote zero or negative values in coins are skipped. When amount == 0 the answer is always 0.
Return exactly {"drawdown": [...], "profit": ..., "coins": ...}.
Constraints
0 <= len(pnl) <= 10^50 <= len(prices) <= 10^50 <= len(coins) <= 10^3-10^9 <= pnl[i] <= 10^90 <= prices[i] <= 10^90 <= amount <= 10^4-10^9 <= coins[i] <= 10^9(non-positive denominations are ignored)
Examples
Example 1
Input: analyze_series_and_amount([100, 120, 90, 95, 80], [7, 1, 5, 3, 6, 4], [1, 2, 5], 11)
Output: {'drawdown': [-40, 2, 4], 'profit': 5, 'coins': 3}
Example 2
Input: analyze_series_and_amount([5, 4, 3, 2, 1], [7, 6, 4, 3, 1], [2], 3)
Output: {'drawdown': [-4, 1, 4], 'profit': 0, 'coins': -1}
Example 3
Input: analyze_series_and_amount([10, 10, 12, 12], [1, 2, 3], [2, 4], 7)
Output: {'drawdown': [0, -1, -1], 'profit': 2, 'coins': -1}
Example 4
Input: analyze_series_and_amount([0, -5, -2, -10, -3, 4], [3, 8, 2, 5, 1, 7], [2, 4], 7)
Output: {'drawdown': [-10, 1, 3], 'profit': 6, 'coins': -1}
Hints
Hint 1
For the drop, comparing every pair is wasteful: carry the largest value seen so far (plus its position) and measure each new point against it.
Hint 2
The trade gain is the same pass with the extremes swapped — carry the smallest price seen so far rather than the largest.
Hint 3
For coins, greedy can be wrong (coins [1,3,4] making 6), so build a DP table where dp[x] is the fewest coins summing to x, filled in increasing x.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
The first two parts share one technique; the third needs dynamic programming.
Part 1 — steepest drop. Every drop pairs a peak at p with a later-or-equal point t. For a fixed t, the most negative pnl[t] - pnl[p] comes from taking p at the largest value seen so far, i.e. the running peak. So a single left-to-right pass covers every candidate pair, avoiding the O(n^2) brute force. Raise the running peak before measuring the current point, so a brand-new high registers a drop of 0 instead of a positive number. The comparisons are deliberately strict: > when raising the peak preserves the earliest equal peak, and < when recording a drop preserves the first trough among ties. Starting the answer at 0 means a series that never declines (or an empty one) yields [0, -1, -1].
Why it is correct: minimizing pnl[t] - pnl[p] over p <= t and then over t is the same as minimizing pnl[t] - max(pnl[0..t]) over t, which is precisely the scan; capturing peak_index + 1 and t at the moment the running minimum is beaten produces the requested indices.
Part 2 — best trade. This mirrors part 1: for each sell day, the ideal buy day is the cheapest price strictly before it. Keep the running minimum and update profit = max(profit, price - cheapest). Because profit begins at 0, a strictly falling or flat series (or fewer than two days) returns 0. A self-trade with j = i would contribute 0, so the order of the two updates cannot inflate the result.
Part 3 — fewest coins. Greedy is unsafe: with coins [1, 3, 4] and target 6, grabbing the largest coin first gives 4+1+1 (three coins) whereas 3+3 needs only two. So define dp[x] as the fewest coins summing exactly to x, set dp[0] = 0, and initialize the rest to a sentinel of amount + 1 (bigger than any feasible count). For each x in increasing order, try every positive coin c <= x and set dp[x] = min(dp[x], dp[x - c] + 1). This is optimal substructure: an optimal solution for x ends with some coin c, and what remains must be optimal for x - c. Processing amounts in increasing order guarantees dp[x - c] is final before use. If dp[amount] is still the sentinel at the end, the target cannot be formed, so return -1.
Complexity. Part 1 runs in O(len(pnl)) time with O(1) extra space. Part 2 runs in O(len(prices)) time with O(1) extra space. Part 3 runs in O(amount * len(coins)) time and O(amount) space — pseudo-polynomial in the numeric value of amount.
from typing import Dict, List
def analyze_series_and_amount(pnl: List[int], prices: List[int], coins: List[int], amount: int) -> Dict[str, object]:
# 1) Steepest drop: one pass carrying the running peak and its position.
if not pnl:
drawdown = [0, -1, -1]
else:
peak_value = pnl[0]
peak_index = 0
worst = 0
start = -1
end = -1
for i in range(1, len(pnl)):
if pnl[i] > peak_value:
peak_value = pnl[i]
peak_index = i
current = pnl[i] - peak_value
if current < worst:
worst = current
start = peak_index + 1
end = i
drawdown = [worst, start, end]
# 2) Best single trade: track the cheapest earlier price.
profit = 0
if prices:
cheapest = prices[0]
for price in prices[1:]:
gain = price - cheapest
if gain > profit:
profit = gain
if price < cheapest:
cheapest = price
# 3) Fewest coins: bottom-up DP across amounts.
usable = [c for c in coins if c > 0]
unreachable = amount + 1
dp = [unreachable] * (amount + 1)
dp[0] = 0
for target in range(1, amount + 1):
best = dp[target]
for coin in usable:
if coin <= target:
candidate = dp[target - coin] + 1
if candidate < best:
best = candidate
dp[target] = best
coin_count = -1 if dp[amount] == unreachable else dp[amount]
return {"drawdown": drawdown, "profit": profit, "coins": coin_count}