Compute max profit from one stock trade
FlipsterSoftware Engineer · Technical ScreenLast updated
This question evaluates a candidate's understanding of array-based data processing, difference maximization, and basic algorithmic optimization for time-series inputs. It is commonly asked in Coding & Algorithms interviews to assess fundamental practical programming ability and attention to edge cases (e.g.
Given an integer array prices where prices[i] is the stock price on day i, compute the maximum profit you can achieve by choosing at most one day to buy and a later day to sell.
- You may complete 0 or 1 transaction.
- You must buy before you sell.
Input
prices: array of integers,n >= 1
Output
- Maximum possible profit (integer).
Example
- Input:
[7, 1, 5, 3, 6, 4] - Output:
5(buy at 1, sell at 6)
Edge cases
- Prices always decreasing → return
0.
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.