You are interviewing for a software engineering role at a FAANG-level company.
The interviewer presents a real-world business scenario instead of a direct algorithmic question.
A global financial analytics platform tracks the daily stock price of a company.
Your system is allowed to perform at most one transaction, defined as:
- Buying one stock on a single day
- Selling that same stock on a future day
The goal is to maximize profit from this single transaction.
However, the system must obey strict trading rules:
- You must buy before you sell
- You may choose not to trade if no profit is possible
- The solution must be efficient, as price data can be very large
This is a classic coding interview problem might used by Google, Amazon, Netflix, Meta, Apple, and Microsoft to test greedy thinking, array traversal, and optimization skills.
Your Task
Given an array prices where prices[i] represents the stock price on the i-th day:
👉 Return the maximum profit you can achieve from one buy and one sell.
👉 If no profit is possible, return 0.
Input Format
prices: An array of integers representing daily stock prices
Output Format
- A single integer representing the maximum profit
Examples
Example 1:
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5
Explanation: Buy on day 2 at price 1, sell on day 5 at price 6.
Profit = 6 - 1 = 5.
Example 2:
Input: prices = [7, 6, 4, 3, 1]
Output: 0
Explanation: Prices keep decreasing. No profitable transaction is possible.