Maximum Profit from One Stock Purchase and a Later Sale
Company: Xiaohongshu
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Technical Screen
Overview: Given one stock's price on each of several consecutive days, compute the maximum profit from buying one share and selling it on a strictly later day, or zero if no trade makes money. It tests efficient reasoning over an array under large input bounds and careful handling of edge cases such as falling prices or a single day.
Constraints
- 1 <= n <= 100000, where n is the length of prices
- 0 <= prices[i] <= 1000000000
- The answer is at most 1000000000, which fits in a signed 32-bit integer
- A trade is one purchase on day i and one sale on day j with i < j; at most one trade is allowed, and not trading is allowed and gives profit 0
Examples
Input: ([8, 3, 6, 2, 9, 4],)
Expected Output: 7
Explanation: Source example 1: buy at 2 on day 3, sell at 9 on day 4 for a profit of 7; no other pair gives more.
Input: ([9, 7, 4, 1],)
Expected Output: 0
Explanation: Source example 2 and the strictly decreasing case: every later price is lower, so not trading (profit 0) is best.
Hints
- The answer is never negative: not trading is always one of the allowed choices, so 0 is a floor on the result.
- For a fixed selling day, only one thing about the earlier days matters when you want the largest difference.
- The order of days is what makes this more than max(prices) - min(prices): the cheapest day can come after the most expensive one.