Best Time to Buy and Sell Stock
You are given an array prices where prices[i] is the price of a given stock on the i-th day. You want to maximize your profit by choosing a single day to buy one stock and choosing a different future day to sell it. Return the maximum profit you can achieve from this transaction. If no profit is possible, return 0.
This is a classic one-pass DP problem. The key insight is to track the minimum price seen so far and the maximum profit achievable at each step. As we iterate through prices, we update the minimum price if the current price is lower. We also calculate the profit if we sold at the current price (current price minus minimum price) and update the maximum profit if this is higher.
At any point, the minimum price so far represents the best buying opportunity we have seen. The profit calculation represents the profit if we sold today. The maximum profit variable keeps the best profit across all days. This O(n) algorithm uses only O(1) extra space.
Edge cases include a single day (no transaction possible, return 0), a strictly decreasing price (no profit possible, return 0), and equal prices throughout (no profit, return 0).
The one-pass DP approach works because the optimal solution only needs the minimum price seen so far. This is a simple example of stateful DP where only one variable (min price) captures all necessary information from previous states.
Example Input & Output
Decreasing prices, no profit possible.
Buy at 1, sell at 2.
Equal prices, no profit.
Buy at 1 (day 2), sell at 6 (day 5), profit 5.
Only one price, no transaction.
Algorithm Flow

Solution Approach
Track min price and max profit in one pass. Update min price when lower, update max profit when higher.
Time O(n), Space O(1).
Best Answers
class Solution {
public int solution(int[] prices) {
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < prices.length; i++) {
if (prices[i] < minPrice) minPrice = prices[i];
int profit = prices[i] - minPrice;
if (profit > maxProfit) maxProfit = profit;
}
return maxProfit;
}
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
