Maximum Profit from One Stock Purchase and One Later Sale
Company: Amazon
Role: Software Engineer
Category: Coding & Algorithms
Difficulty: medium
Interview Round: Onsite
Overview: Given a stock's daily prices, return the largest profit from one purchase followed by one sale on a strictly later day, or zero when no trade makes money. It tests efficient reasoning about ordered buy and sell pairs in arrays of up to a hundred thousand prices.
Read the full Amazon Software Engineer interview experience this question came from
Constraints
- 1 <= len(prices) <= 10^5
- 0 <= prices[i] <= 10^4
- The output is a single integer.
- The answer is between 0 and 10^4 and fits in a signed 32-bit integer.
Examples
Input: ([8, 2, 6, 4, 9, 3],)
Expected Output: 7
Explanation: Source example 1: buy at 2 on day 1 and sell at 9 on day 4 for a profit of 7.
Input: ([9, 7, 4, 2],)
Expected Output: 0
Explanation: Source example 2: prices only fall, so no trade is profitable and the answer is 0.
Hints
- Making no trade is always allowed, so the answer is at least 0.
- The sell day must come after the buy day, so the overall lowest and highest prices form a valid trade only when the lowest comes first. Example 2 shows the best trade can skip the highest price.
- With up to 10^5 days, comparing every pair of days takes about 5 * 10^9 checks; look for a way to handle each day once.