Advertisement

Best Time to Buy and Sell Stock - LeetCode 121 Solution

Best Time to Buy and Sell Stock - Complete Solution Guide

Best Time to Buy and Sell Stock is LeetCode problem 121, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.

Problem Statement

You are given an array prices where prices[i] is the price of a given stock on the i th 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 . 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

Detailed Explanation

This problem asks us to pinpoint the optimal single day to buy a stock and a subsequent single day to sell it, all with the goal of maximizing our profit. The input is a simple array where each element `prices[i]` represents the stock's value on day `i`. The crucial constraint here is that you *must* sell on a day *after* you buy. You can't buy and sell on the same day, nor can you sell before you've bought the stock. What makes this interesting isn't just finding the absolute lowest price and the absolute highest price in the `prices` array. For instance, in `[7,1,5,3,6,4]`, the lowest price is 1 and the highest is 7. But you can't buy at 1 (day 2) and sell at 7 (day 1) because the buy date must precede the sell date. Instead, we need to find the largest difference `prices[sell_day] - prices[buy_day]` such that `sell_day > buy_day`. If no such profitable transaction is possible (e.g., prices only ever go down), we should return 0. The challenge lies in efficiently iterating through the prices while respecting the 'buy before sell' rule. A naive approach might involve checking every possible buy day and then every possible sell day after it, leading to a much slower solution. We need a way to keep track of the best buying opportunity up to any given point as we consider potential selling days.

Solution Approach

The provided solution employs a clever single-pass strategy to tackle this problem. It iterates through the `prices` array just once, maintaining two critical pieces of information: `min_price` and `max_profit`. `min_price` tracks the lowest stock price encountered *so far* as we traverse the array. When we are at `prices[i]`, `min_price` holds the absolute minimum value from `prices[0]` to `prices[i-1]` (or `prices[i]` itself if `prices[i]` is a new minimum). This is crucial because for any `prices[i]` we consider as a potential selling point, the optimal buy point *before or on day i* is precisely this `min_price`. We update `min_price = min(min_price, price)` to ensure it always reflects the best buying opportunity seen up to the current day. Simultaneously, `max_profit` tracks the highest profit calculated across all days. For each `price` (current day's stock price), we calculate a potential profit: `price - min_price`. This difference represents the profit if we were to sell on the current day (`price`) after having bought on the day corresponding to `min_price`. Since `min_price` is always updated to be the lowest price encountered *up to or including the current day*, this profit calculation inherently respects the 'buy before sell' constraint. We then update `max_profit = max(max_profit, current_potential_profit)` to retain the highest profit found so far. By the time the loop finishes, `max_profit` will hold the maximum achievable profit from any single transaction.

Step-by-Step Algorithm

  1. Step 1: Initialize `min_price` to a very large value (positive infinity in Python, Integer.MAX_VALUE in Java, INT_MAX in C++) and `max_profit` to 0.
  2. Step 2: Iterate through the `prices` array.
  3. Step 3: For each `price`, update `min_price` to the minimum of `min_price` and `price`.
  4. Step 4: Calculate the current profit as `price - min_price`.
  5. Step 5: Update `max_profit` to the maximum of `max_profit` and the current profit.
  6. Step 6: After iterating through all prices, return `max_profit`.

Key Insights

  • The core insight is to continuously track the lowest price encountered *up to the current day*. For any given `price` we're currently looking at as a potential sell point, the best possible profit comes from buying at the lowest point *before or on* that day.
  • This problem doesn't require us to store all possible buy/sell pairs or look ahead into the future. By maintaining `min_price` as a running minimum, we ensure that every potential profit calculation (`current_price - min_price`) correctly considers the 'buy before sell' constraint with the most optimal buy point seen so far.
  • The solution's elegance comes from its O(N) time complexity and O(1) space complexity. A single pass through the array, updating just two variables, is sufficient because the global maximum profit can always be found by comparing the current price with the best preceding buy price.

Complexity Analysis

Time Complexity: O(n)

Space Complexity: O(1)

Topics

This problem involves: Array, Dynamic Programming.

Companies

Asked at: AQR Capital Management, Accenture, Accolite, Agoda, Airtel, Akamai, American Express, Arista Networks, Atlassian, BNY Mellon, Bank of America, Bentley Systems, BlackRock, Blizzard, Bolt, ByteDance, CME Group, Capgemini, Capital One, Cisco, Citadel, Citigroup, Cloudera, CrowdStrike, DE Shaw, DRW, Deloitte, Deutsche Bank, DevRev, EPAM Systems, Expedia, FPT, Flipkart, FreshWorks, Garmin, Goldman Sachs, Groww, HSBC, HashedIn, IBM, Infosys, Instacart, Intel, Intuit, J.P. Morgan, LinkedIn, Mastercard, Media.net, Microstrategy, Millennium, Morgan Stanley, Myntra, Netflix, Nutanix, Nvidia, Ola Cabs, Optiver, Oracle, Ozon, Palantir Technologies, PayPal, PhonePe, Pwc, QBurst, RBC, Rakuten, Remitly, Robinhood, Roblox, SAP, Salesforce, Samsung, ServiceNow, Shopee, Siemens, Slice, Snap, Snapdeal, Snowflake, Societe Generale, Sony, Sprinklr, Swiggy, Tech Mahindra, Tekion, Tesla, The Trade Desk, ThoughtWorks, Tiger Analytics, TikTok, Toast, Tripadvisor, Turing, Two Sigma, UBS, UKG, Uber, VMware, Visa, Walmart Labs, Yahoo, Yandex, Zoho, Zoox, Zopsmart, athenahealth, carwale, eBay, josh technology, opentext, tcs, zeta suite.