cswork / libraryOpen practice workspace

Coding questions · Meta

Compute Stock Profit with One or Unlimited Transactions

Compute maximum stock profit for both one transaction and unlimited nonoverlapping transactions in linear time, returning zero when no positive trade is available.

Problem

Given daily stock prices, return two values: the maximum profit when at most one buy-sell transaction is allowed, and the maximum profit when any number of non-overlapping transactions is allowed. You may hold at most one share at a time, and a sale must occur after its corresponding purchase.

Constraints & Assumptions

  • The price list contains between 1 and 200,000 positive integers.
  • Prices fit in 32-bit signed integers; use 64-bit arithmetic for total profit.
  • Buying and selling on the same day adds no profit and is unnecessary.
  • Return zero for a strategy that cannot make a positive profit.

Clarifications

  • There are no fees, cooldown periods, or limits beyond the one-share holding rule.
  • Unlimited transactions cannot overlap, but a new buy may follow an earlier sale.
  • Return [oneTransactionProfit, unlimitedTransactionsProfit].

Examples

prices = [7, 1, 5, 3, 6, 4]
output = [5, 7]

Hints

Hint: One transaction

Track the lowest price seen before each possible selling day.

Hint: Unlimited transactions

Identify every positive day-to-day increase that can be captured without overlapping holdings.

Compute Stock Profit with One or Unlimited Transactions

Given a nonempty list of positive daily stock prices, return [oneTransactionProfit, unlimitedTransactionsProfit]. The first value is the maximum profit using at most one buy followed by one later sale. The second is the maximum profit using any number of non-overlapping buy-sell transactions while holding at most one share at a time. There are no fees or cooldowns, a new buy may follow an earlier sale, and a strategy that cannot earn positive profit returns zero.

Hints

  1. Track the lowest price before each possible selling day for the one-transaction result.
  2. For unlimited transactions, capture every positive day-to-day increase.

Approach

Scan prices once. For the one-transaction objective, keep the lowest price seen before or on the current day and maximize the difference between the current price and that minimum. For unlimited transactions, add every positive adjacent increase. Each rising run's adjacent gains telescope to the same profit as buying at its start and selling at its end, and separate rising runs correspond to non-overlapping holdings. Declines are skipped because holding across them cannot improve an unlimited strategy. Use 64-bit totals.

  • Time complexity: O(n).
  • Space complexity: O(1) auxiliary space.