Compute max profit from one stock trade
Problem Description
You are given an integer array prices, where prices[i] represents the price of a given stock on day i. Your task is to compute the maximum profit you can achieve by completing at most one transaction.
A transaction consists of choosing a single day to buy a stock and a later day to sell it. You are allowed to complete zero or one transaction. If no profit can be made, the maximum profit is 0.
Constraints
- The
pricesarray will have at least one element (n >= 1). - You must buy the stock before you sell it.
Input
prices: An array of integers representing daily stock prices.
Output
- An integer representing the maximum possible profit.
Example
- Input:
[7, 1, 5, 3, 6, 4] - Output:
5(Achieved by buying at price 1 and selling at price 6.)
Edge Cases
- If prices are always decreasing, the maximum profit should be
0.
AI interview prep
Core dilemma
Efficiently identifying the optimal buy point to maximize profit given a single transaction constraint and the 'buy before sell' rule.
1 tradeoff and 2 stress tests locked
Interview prep
Unlock the interviewer X-Ray rubric, tradeoff matrix, stress tests, clarifying questions, and key concepts.
Compute max profit from one stock trade
Problem Description
You are given an integer array prices, where prices[i] represents the price of a given stock on day i. Your task is to compute the maximum profit you can achieve by completing at most one transaction.
A transaction consists of choosing a single day to buy a stock and a later day to sell it. You are allowed to complete zero or one transaction. If no profit can be made, the maximum profit is 0.
Constraints
- The
pricesarray will have at least one element (n >= 1). - You must buy the stock before you sell it.
Input
prices: An array of integers representing daily stock prices.
Output
- An integer representing the maximum possible profit.
Example
- Input:
[7, 1, 5, 3, 6, 4] - Output:
5(Achieved by buying at price 1 and selling at price 6.)
Edge Cases
- If prices are always decreasing, the maximum profit should be
0.