KatInterview

Max Gains from Single and Multi-Trade Asset Strategies

Greedy & IntervalsAuto-graded · 17 test cases
MediumAuto-gradedGreedy & Intervalsarraysgreedydynamic-programming

Last updated

Calculate maximum achievable gain for an asset sequence under single-trade and unlimited-trade restrictions.

Given a list of positive integers representing the sequential daily values of an asset, calculate the maximum possible returns for two different trading strategies:

  1. Single Trade Strategy: You may complete at most one transaction (buy once and sell once on a later day).
  2. Unlimited Trades Strategy: You may complete as many non-overlapping transactions as you like (you can buy and sell multiple times, but you can hold at most one unit of the asset at any point, and a sale must take place after its corresponding buy).

If a strategy cannot yield any positive profit (for instance, if prices strictly decrease or remain flat), the return for that strategy should be 0.

Return a list of two integers: [max_single_trade_gain, max_unlimited_trades_gain].

Constraints

  • 1 <= len(prices) <= 200,000
  • 1 <= prices[i] <= 2^31 - 1
  • Processing must run in $O(N)$ time.

Examples

Example 1

Input: compute_stock_profit([7, 1, 5, 3, 6, 4])

Output: [5, 7]

Hints

Hint 1

For a single trade, if you sell on day j, what is the best day i < j to buy?

Hint 2

For unlimited trades, notice that selling at peak B and buying at valley A yields the same gain as accumulating every single daily positive price rise between A and B.

Hint 3

You can compute both metrics concurrently in a single pass through the prices array.