Given daily stock prices, return the largest profit obtainable from at most one purchase followed by one later sale, or zero when no profitable trade exists.
## Problem
Given daily stock prices, choose at most one buy followed by at most one sell and return the maximum possible profit. The sale must occur on a later day than the purchase. Return `0` when no profitable trade exists.
### Function Contract
Implement `maxSingleTradeProfit(prices)` and return one integer.
### Constraints & Assumptions
- `0 <= len(prices) <= 200,000`.
- `0 <= prices[i] <= 10^9`.
- You may hold at most one share.
- Transaction fees and taxes are ignored.
### Clarifying Questions to Ask
- May the stock be sold before it is bought? No.
- Is doing nothing allowed? Yes, yielding profit `0`.
- Are multiple transactions allowed? No.
```hint Keep the best purchase seen so far
While scanning from left to right, compare today's price with the minimum earlier price, then update the minimum for future days.
```
### Examples
```text
[7,1,5,3,6,4] -> 5
[7,6,4,3,1] -> 0
[2,4,1] -> 2
```
### Evaluation Focus
- Preserves buy-before-sell order.
- Returns zero for descending, empty, or single-price inputs.
- Runs in `O(n)` time and `O(1)` auxiliary space.
### Extensions to Discuss
1. How would you return the buy and sell indices?
2. What changes if unlimited nonoverlapping transactions are allowed?
3. How would a transaction fee affect the state?
Quick Answer: Given daily stock prices, return the largest profit obtainable from at most one purchase followed by one later sale, or zero when no profitable trade exists.
Given daily stock prices, choose at most one buy followed by at most one sell and return the maximum possible profit. The sale must occur on a later day than the purchase. Return 0 when no profitable trade exists.
Function Contract
Implement maxSingleTradeProfit(prices) and return one integer.
Constraints & Assumptions
0 <= len(prices) <= 200,000
.
0 <= prices[i] <= 10^9
.
You may hold at most one share.
Transaction fees and taxes are ignored.
Clarifying Questions to Ask Guidance
May the stock be sold before it is bought? No.
Is doing nothing allowed? Yes, yielding profit
0
.
Are multiple transactions allowed? No.
Examples
[7,1,5,3,6,4] -> 5
[7,6,4,3,1] -> 0
[2,4,1] -> 2
Evaluation Focus
Preserves buy-before-sell order.
Returns zero for descending, empty, or single-price inputs.
Runs in
O(n)
time and
O(1)
auxiliary space.
Extensions to Discuss
How would you return the buy and sell indices?
What changes if unlimited nonoverlapping transactions are allowed?