Best Time to Buy and Sell Stock | LeetCode 121

AFFILIATE LINKS

Great resource I use to learn algorithms.
40% off Tech Interview Pro: http://techinterviewpro.com/terriblewhiteboard
20% off CoderPro: http://coderpro.com/terriblewhiteboard

The key to this is to buy at the cheapest price and sell at the highest price to the right of the cheapest price. To do this, keep track of the cheapest price and update it any time you find a cheaper price. To find the max profit (assuming you are not on the cheapest stock), subtract the cheapest price from the current stock’s price. This gives you the profit. If this profit is greater than the max profit, make this the new max profit.

/**
 * @param {number[]} prices
 * @return {number}
 */
let maxProfit = function(prices) {
  let minBuyPrice = Infinity; // only buy at the cheapest price
  let maxProfit = 0;

  for (let price of prices) {
    if (price < minBuyPrice) {
      // update the min price if the current price is less than the price
      minBuyPrice = price;
    } else if (price - minBuyPrice > maxProfit) {
      /* update the max profit if the difference between the current price and the current min is greater than the current max profit */
      maxProfit = price - minBuyPrice;
    }
  }

  return maxProfit; 
};