Member-only story
New* JavaScript | Arrays | Coding Interview | Best Time to Buy and Sell Stock
2 min readJun 6, 2021
Today we’ll discuss the popular coding interview problem related to buying and selling stocks. This one is undoubtedly the easiest of them all. We just need to buy and sell a single stock to maximize the profit.
If we can keep a track of the minimum stock price and the maximum profit, we should be able to solve the problem in a single pass.
Input: prices = [7,1,5,3,6,4]
Output: 5Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.
Let’s understand the approach,
- We are trying to find the max of “Profit = Max — Min”
Because we can only sell stocks after we bought them, this problem is one-directional, which means Max is always somewhere right to the Min. - When our Min value is set, we traverse through the array and keep comparing (
prices
[i]-buyPrice
) and previous Profit, and set Profit to whichever is larger - We replace the previous Min when we found a new Min that is lower than it. Because the problem is one-directional, we don’t need to go back and worry about the past, just keep…