101 Logo
onenoughtone

Problem Statement

Stock Profit Maximizer

You are a financial analyst tasked with finding the best opportunity to buy and sell a stock to maximize profit. You have historical data of the stock's price over a period of time, and you want to determine the maximum profit you could have made with a single buy and sell transaction.

Given an array prices where prices[i] is the price of a given stock on the ith day, you want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.

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

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.

Constraints

  • 1 <= prices.length <= 10^5
  • 0 <= prices[i] <= 10^4

Problem Breakdown

To solve this problem, we need to:

  1. The key insight is to find the maximum difference between a future price and a past price.
  2. We can track the minimum price seen so far and calculate the potential profit if we sell at the current price.
  3. This problem can be solved in a single pass through the array, making it an O(n) time complexity solution.
  4. We don't need to consider all possible buy and sell combinations, which would be O(n²).
ProblemSolutionCode
101 Logo
onenoughtone