DEV Community

Discussion on: Best time to buy and sell 📈 (easy)

Collapse
 
kais_blog profile image
Kai • Edited

Thanks for your post! I've tried finding a simpler solution:

const maxProfit = (prices) => {
  if (prices.length === 0) return 0;

  // Calculate maximum profit for each price.
  const profits = prices.map((price, i) => {
    // Find maximum price, ignoring prices before our current price.
    const max = Math.max(...prices.slice(i));
    return max - price;
  });

  // Return maximum profit.
  return Math.max(...profits);
};
Enter fullscreen mode Exit fullscreen mode

I did not test for performance, though. Nevertheless, I think it's more readable.

Collapse
 
santispavajeau profile image
Santiago Salazar Pavajeau

I think your solution is very clever using the spread operator to find the highest profit. I tried to share a solution where the step-by-step is very clear, so it can be rewritten in any language! Thanks again for yours, it is great!

Collapse
 
kais_blog profile image
Kai

Thank you :)