KatInterview

Single Buy-Sell Stock Gain

Greedy & IntervalsAuto-graded · 17 test cases
MediumAuto-gradedGreedy & Intervalsgreedyarrayssliding-window

Last updated

Tests finding the maximum profit from one purchase and one sale in a price sequence using a single-pass greedy approach.

Problem Statement

Given a sequence of daily stock prices, determine the largest gain achievable by purchasing on one day and selling on a strictly later day. If no positive gain is possible, return 0.

You receive an array prices where each element represents the stock price on a particular day (indexed from 0 onward). Your task is to identify the optimal pair of days—one to buy and one to sell—such that the sell day comes after the buy day and the difference is maximized.

Constraints

  • 1 <= len(prices) <= 10^5
  • 0 <= prices[i] <= 10^4

Notes

  • You must buy before you sell (the buy index must be strictly less than the sell index).
  • If the prices never increase (e.g., they are flat or declining), no profitable transaction exists; return 0.
  • You may perform at most one transaction (one buy followed by one sell).

Examples

Example 1

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

Output: 5

Example 2

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

Output: 0

Hints

Hint 1

For each potential sell day, what is the best day to have bought? You don't need to remember every earlier price.

Hint 2

Track the lowest price encountered so far as you scan left to right. This represents your best buying opportunity up to the current day.

Hint 3

A single pass with two variables—minimum price seen and maximum profit found—is sufficient to solve this in O(n) time.