Skip to main content

121. Best Time to Buy and Sell Stock

You are given an array prices where prices[i] represents the price of a stock on the i-th day.

Your goal is to maximize profit by choosing exactly one day to buy and a different later day to sell the stock.

Return the maximum profit you can achieve from the transaction.
If no profit is possible, return 0.


Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6 - 1 = 5.
Note: You cannot buy on day 2 and sell on day 1 because the selling day must come after the buying day.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: The price always drops, so no transaction yields a profit.

Constraints:

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

Instead of checking every possible buy-sell pair, which would be O(n^2) , we track two things in one pass:

  1. The lowest price seen so far (minPrice)
  2. The maximum profit we can make so far (maxProfit)

On each day:

  • If the current price is lower than minPrice, update minPrice (this could be a better buy day).
  • Otherwise, calculate price - minPrice (profit if sold today), and if it's larger than maxProfit, update maxProfit.

Java Solution:

class Solution {
public int maxProfit(int[] prices) {
var minPrice = Integer.MAX_VALUE;
var maxProfit = 0;

for (var price : prices) {
if (price < minPrice) {
minPrice = price;
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice;
}
}
return maxProfit;
}
}

Kotlin Solution:

class Solution {
fun maxProfit(prices: IntArray): Int {
var minPrice = Int.MAX_VALUE
var maxProfit = 0

for (price in prices) {
if (price < minPrice) {
minPrice = price
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice
}
}
return maxProfit
}
}

Scala Solution:

object Solution {
def maxProfit(prices: Array[Int]): Int = {
var minPrice = Int.MaxValue
var maxProfit = 0

for (price <- prices) {
if (price < minPrice) {
minPrice = price
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice
}
}
maxProfit
}
}