Maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
LeetCode-121: You are given an array prices
where prices[i]
is the price of a given stock on the ith
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.
Before we discuss the solution, here are a few observations:
i
maximum price at index j
, we can use those to calculate the maximum result \( \iff j > i\). This is because we can only sell a stock at index \(j\), if we have purchased it in the past at index \(i \enspace | \enspace i < j\).minPrice
.maxProfit
by evaluating: \(max(maxProfit, currPrice - minPrice)\)The following is a java implementation of the above mentioned approach:
public int maxProfit(int[] prices) {
int maxProfit = 0;
int minPrice = prices[0];
for(int currPrice : prices){
// keep track of min price so far
minPrice = Math.min(minPrice, currPrice);
// maxProfit so far = max(maxProfit, currPrice - minPrice)
maxProfit = Math.max(maxProfit, currPrice - minPrice);
}
return maxProfit;
}
With this approach, we are able to find a solution in \(O(n)\) time complexity.
Be notified of new posts. Subscribe to the RSS feed.