Search⌘ K
AI Features

Problem: Best Time to Buy and Sell Stock

Explore how to solve the best time to buy and sell stock problem using JavaScript arrays. Learn to implement a single pass approach that tracks the minimum price and maximum profit to find the optimal transaction day. Understand the code logic and analyze the solution's time and space complexity to build efficient array-based algorithms.

Statement

You are given an array prices where prices[i] represents the price of a stock on the ithi^{th} day.

Your goal is to maximize your profit by selecting a single day to buy the stock and a different day in the future to sell it. The sell day must come strictly after the buy day.

Return the maximum profit achievable from this transaction. If no profit is possible, return 00.

Note: You must buy the stock before you sell it, meaning the buy day must have a smaller index than the sell day.

Constraints:

    ...