The Best Time to Buy and Sell Stock problem involves finding the maximum profit you can achieve by buying and selling a stock. You are given an array where each element represents the stock price on a given day. You can only complete one transaction (buy one and sell one share).
class Solution {
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for (int price : prices) {
if (price < minPrice) {
minPrice = price; // Update the minimum price
} else if (price - minPrice > maxProfit) {
maxProfit = price - minPrice; // Update the maximum profit
}
}
return maxProfit;
}
}
O(N)
, where N
is the number of days (length of the prices array).O(1)
, as no additional space is used.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.