Episode 02 - Best time to buy the stock

Episode 02 - Best time to buy the stock

·

2 min read

In this episode, we are going to explain one of the famous questions asked in a JavaScript interview. You will be given an array of integers that represents the prices of stock each day. Your task is to find the best buying and selling price that will give you maximum profit.

The array will be like [6, 1, 2, 5, 7] and the output will be 6. The lowest price of the stock is on the 2nd day which is 1 and the highest price is on the 5th day which is 7. So buying at the price of 1 and selling at 7 will give us a profit of 6.

Now let's explore the way to find this in JavaScript.

function findMaximumProfit(prices) {
  const length = prices.length;
  let buyPrice = prices[0];
  let maxProfit = 0;

  for (let i = 1; i < length; i++)  {

    if (buyPrice > prices[i]) {
      buyPrice = prices[i];
    } else {
      maxProfit = prices[i] - buyPrice;
    }    
  }
  return maxProfit;
}

console.log(findMaximumProfit([6, 1, 2, 5, 7])); //6

Code Explanation:

We will first declare a few variables: length to store the length of the variable, declare buyprice and assign the first price from the array, and maxProfit to 0. We will start the iteration from the first index since we already assigned the 0th value to the variable. In each iteration, we will check if the buyPrice is greater than the current price. If so then, we will modify the value to that price. Otherwise, we will check the profit buy subtracting both values. At the end of the loop we will return the value of maxProfit.

This array returns the profit as 6. We need to buy the stock at the price of 1 and sell at the price of 7.

There is also another variation of this questions where the interviewer might ask for the buying and selling date instead of the profit. We can solve that also easily, by tweaking this same code.

function findBuySellDate(prices) {
  const length = prices.length;
  let buyPrice = prices[0];
  let maxProfit = 0;
  let buyDate = 0;
  let dates = [];

  for (let i = 1; i < length; i++)  {
    if (buyPrice > prices[i]) {
      buyPrice = prices[i];
      buyDate = i;
    } else {
      maxProfit = prices[i] - buyPrice;
      dates = [buyDate, i];
    }    
  }
  return dates;
}

console.log(findBuySellDate([6, 1, 2, 5, 7])); // [1, 4]

Running this function with the same code now, will return the indices for the buy and sell.

Check it out on our YouTube