121. Best Time to Buy and Sell Stock
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.Intuition
Approach
Complexity
Code
Last updated
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.Last updated
public int maxProfit(int[] prices) {
int minPrice = Integer.MAX_VALUE, maxPrice = Integer.MIN_VALUE,maxProfitTillNow = 0;
for (int i = 0; i < prices.length; ++i) {
// If current day price is the lowest
// reset the maxPrice also as it means we are buying on current day
if(prices[i] < minPrice ) {
minPrice = prices[i];
maxPrice = prices[i];
} else {
// Update the maxPrice by comparing price with current day price
maxPrice = Math.max(maxPrice,prices[i]);
// Recalculate the max profit we can achieve till date
maxProfitTillNow = Math.max(maxProfitTillNow,maxPrice-minPrice);
}
}
return Math.max(maxProfitTillNow,maxPrice - minPrice);
}