JSFiddle - React, Tailwind, and code Playground

by Shridhar Baddur

JavaScript

var maxProfit = function(prices) {
  let n = prices.length;
  if (n < 2) return 0;
  let left = 0;		// left is buying pointer
  let right = 1;	// right is selling pointer
  let maxProfit = 0;

  while (right < n) {
    if (prices[left] < prices[right]) {
      let profit = prices[right] - prices[left];
      maxProfit = Math.max(profit, maxProfit);
    } else {
      left = right;
    }
    right++;
  }
  return maxProfit;
};