KatInterview

Single Buy-Sell Transaction for Maximum Gain

Arrays & HashingAuto-graded · 18 test cases
MediumAuto-gradedArrays & Hashingarraysgreedyoptimization

Last updated

Tests optimal single-pass tracking of minimum buy price to maximize profit from one stock transaction.

You receive a sequence of stock prices over consecutive days. Your task is to determine the largest gain possible from buying on one day and selling on a strictly later day. If no profitable transaction exists, report zero.

Write a function that accepts a list of daily prices and returns the maximum achievable profit.

Constraints

  • 1 <= len(prices) <= 10^5
  • 0 <= prices[i] <= 10^4
  • You must buy before you sell (the buy day index must be strictly less than the sell day index)
  • You may complete at most one transaction (one buy followed by one sell)
  • If no profit is possible, return 0

Examples

Example 1

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

Output: 5

Example 2

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

Output: 0

Hints

Hint 1

Think about what information you need to track as you scan through the prices from left to right.

Hint 2

For each potential sell day, what was the best possible buy day before it?

Hint 3

You only need two variables: the lowest price seen so far and the best profit found so far.