Leetcode 121. 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 day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0
.
Input: [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.
Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done, so the maximum profit is 0.
1 <= prices.length <= 10^5
0 <= prices[i] <= 10^4
Q: Can we buy and sell the stock on the same day? A: No, we must buy on one day and sell on a different day in the future.
Q: What do we return if there is no way to achieve a profit?
A: Return 0
.
Q: Is it guaranteed that prices will not be empty? A: Yes, as per the constraints, prices.length is at least 1.
Initialize Variables: Create two variables, minPrice
to keep track of the minimum price encountered so far, and maxProfit
to store the maximum profit found.
minPrice
to be the minimum of minPrice
and the current price (this ensures we always buy at the lowest possible price up to the current day).minPrice
).maxProfit
to be the maximum of maxProfit
and the potential profit calculated.maxProfit
.public class Solution {
public int maxProfit(int[] prices) {
if(prices == null || prices.length == 0) {
return 0;
}
int minPrice = Integer.MAX_VALUE;
int maxProfit = 0;
for(int price : prices) {
if(price < minPrice) {
minPrice = price;
} else if(price - minPrice > maxProfit) {
maxProfit = price - minPrice;
}
}
return maxProfit;
}
}
prices
array). This is because we traverse the list of prices once.This approach ensures we get the maximum profit possible by keeping track of the lowest price to buy and the highest potential profit at each step.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?