Search⌘ K
AI Features

Best Time to Buy and Sell Stock

Explore how to apply greedy techniques to identify the best day to buy and sell stock within an array of prices. Learn to implement an optimal solution that maximizes profit in linear time using constant space. This lesson helps you understand the problem constraints and develop a clear approach to solve the problem effectively.

Statement

Given an array, prices, where prices[i] represent the price of a stock on the i-th day, maximize profit by selecting a single day to buy the stock and a different day in the future to sell it.

Return the maximum profit that can be achieved from this transaction. If no profit can be made, return 0.

Constraints:

  • We can’t sell before buying a stock, that is, the array index at which stock is bought will always be less than the index at which the stock is sold.

  • 11 ...