Best Time to Buy and Sell Stock Lab

53.8% Acceptance

In this lab, you'll be implementing a function to find the maximum profit you can achieve by choosing a single day to buy one stock and choosing a different day in the future to sell that stock. You are given an array prices, where prices[i] is the price of a given stock on the ith day.

To polish your skills, you must focus on writing a bug-free, efficient solution to maximize profit. In this lab, we'll provide you with a series of challenges that will guide you to create an optimized solution.

Problem Description

Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 5
Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.

Note that buying on day 2 and selling on day 1 is not allowed because you must buy before you sell.

Example 2:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: In this case, no transactions are done and the max profit = 0.

Example 3:

Input: prices = [3,3,5,0,0,3,1,4]
Output: 4
Explanation: Buy on day 4 (price = 0) and sell on day 8 (price = 4), profit = 4-0 = 4. This is the maximum profit we can achieve.


  • 1 <= prices.length <= 105
  • 0 <= prices[i] <= 104


  1. Implement the maxProfit function that takes an array of stock prices and returns the maximum profit.
  2. Export the maxProfit function as an ESM export.
  3. Ensure that your solution is efficient and optimized to have a minimum time complexity.
  4. Make sure to exort the function using the ESM export