Hone logo
Hone
Problems

Maximize Profit: Best Time to Buy and Sell Stock

You're given a list of stock prices for consecutive days. Your goal is to find the maximum profit you can achieve by buying the stock on one day and selling it on a later day. This is a fundamental problem in algorithmic trading and data analysis, where understanding price fluctuations to maximize gains is crucial.

Problem Description

Given an array of integers prices, where prices[i] is the price of a given stock on the i-th day, determine the maximum profit you can achieve. To make a profit, you must buy before you sell. If you cannot achieve any profit (i.e., prices only decrease or stay the same), you should return 0.

Key Requirements:

  • You can only complete at most one transaction (i.e., buy one and sell one share of the stock).
  • You cannot sell a stock before you buy one.

Expected Behavior: The function should return a single integer representing the maximum possible profit.

Edge Cases:

  • An empty input array.
  • An input array with only one element.
  • An input array where prices are strictly decreasing.
  • An input array where prices are strictly increasing.

Examples

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 = [1, 2, 3, 4, 5]
Output: 4
Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4
  • The solution should be efficient enough to handle large input sizes.

Notes

Consider how you can efficiently track the minimum price seen so far as you iterate through the prices array. This will help you determine the maximum possible profit at each step.

Loading editor...
plaintext