Skip to content

Instantly share code, notes, and snippets.

@carl-parrish
Created December 26, 2017 03:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carl-parrish/652dbbfc38aa588e6a7939b0bedf3656 to your computer and use it in GitHub Desktop.
Save carl-parrish/652dbbfc38aa588e6a7939b0bedf3656 to your computer and use it in GitHub Desktop.
Max Stock Profit
function maxStockProfit(pricesArr) {

  const Price = {
    'buy': 0,
    'sell': 0,
    'change': true
  };
  
  
  return pricesArr.reduce((maxProfit, currentPrice, indx, arr)=> {
    Price.buy = (Price.change) ? currentPrice : Price.buy;
    Price.sell = arr[indx+1];
    
    if(Price.sell < Price.buy) {
      Price.change = true;
    } else {
      let tempProfit = Price.sell - Price.buy;
      maxProfit =  (tempProfit > maxProfit) ? tempProfit : maxProfit;
      Price.change = false;
    }
    
    return maxProfit;
  }, -1);
  
  
}

console.log(maxStockProfit([10,18,4,5,9,6,16,12]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment