Buy Sell Profit

by jacobwsmith

JavaScript

/*

code challenge - June 5, 2019 via Manuel

Given an array of prices as a parameter. This array represents a single day  of stock Prices so, for example, 
if we pass this stock array [32,46,26,38,40,48,42] into our function, we are saying that our stock started at 
$32  then went up to $46 then went down to $26 and so on, so this  array just depicts how our stock has 
changed throughout the day. What our function determined for us is what’s the max profit that we could have 
made on that stock, so we have to find what is the best price to buy the stock at and what is the best price 
to sell the stock at for us to make the highest profit. So using the same array, we will expect to return an 
object that will contain a key call ‘buy’ with a value of the best price to buy, a key call sell with the best 
price to sell as a value,   and profit whit the total profit, for example.
{
 ‘buy’: 26,
 ‘sell’: 48,
 ‘profit’: 22
}


const maxProfit = function(priceArray){
// takes an array of  prices as a parameter
// return and object  with the best price to sell, to buy, and the profit
}
*/

//////////// SOLUTION ////////////
const maxProfit = function([buy, ...sellArray]) {
  // NOTE: "buy" is kept outside loop and used to find the minimum
  return sellArray.reduce((prev, sell) => {
      const profit = sell - buy;
      if (prev.profit >= profit) {
        if (profit < 0) {
          buy = sell; // set new buy minimum
        }
        return prev; // return prev
      }
      return { buy, sell, profit }; // return updated prev
    },
    { buy: 0, sell: 0, profit: 0 } // initialize prev
  );
};

//////////// TESTS ///////////////
{
  const input = [32, 46, 26, 38, 40, 48, 42];
  const expected = { buy: 26, sell: 48, profit: 22 };
  console.log(JSON.stringify(maxProfit(input)) === JSON.stringify(expected));
}
{
  const input = [2, 4, 3, 1, 2, 2, 2];
  const expected = { buy: 2, sell: 4, profit: 2 };
  console.log(JSON.stringify(maxProfit(input)) ===...