Search⌘ K
AI Features

Problem: Best Time to Buy and Sell Stock

Explore how to determine the best time to buy and sell stock by analyzing an array of prices in a single pass. Learn to track the minimum price and update maximum profit efficiently to solve this problem with O(n) time and O(1) space complexity using C++.

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:

    ...