13 April 2024

Easy

121. Best Time to Buy and Sell Stock

Link: https://leetcode.com/problems/best-time-to-buy-and-sell-stock

Description: Given an array of stock prices, find the maximum profit that can be made by buying and selling a stock.

Solution:

In this problem, we need to find the maximum profit that can be made by buying and selling a stock. We can do this by keeping track of the minimum price seen so far and the maximum profit that can be made by selling the stock at the current price. We iterate through the prices and update the minimum price and maximum profit accordingly.

/**
 * @param {number[]} prices
 * @return {number}
 */

var maxProfit = function (prices) {
  let minPrice = Infinity // Initialize minPrice to the highest possible value
  let maxProfit = 0 // Initialize maxProfit to 0

  for (const price of prices) {
    minPrice = Math.min(price, minPrice) // Update minPrice to the lowest seen so far
    maxProfit = Math.max(maxProfit, price - minPrice) // Calculate profit and update maxProfit if current is higher
  }

  return maxProfit // Return the highest profit found
}