Taro Logo

Best Time to Buy and Sell Stock

Easy
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+69
More companies
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
Profile picture
7K views
Topics:
ArraysDynamic Programming

You are 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.

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 <= 105
  • 0 <= prices[i] <= 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should we return if the input array is empty or has only one element?
  2. Can the stock prices contain negative numbers or zeros, or are they strictly positive integers?
  3. If the prices are strictly decreasing (meaning no profit can ever be made), should the function return 0?
  4. Are we guaranteed that the input is a valid array, or do we need to handle null or undefined inputs?
  5. Is there any restriction on the maximum possible price value that could cause integer overflow?

Brute Force Solution

Approach

Imagine you are looking at a history of daily prices for a single stock and want to figure out the absolute best days to buy and sell for maximum profit. The brute force approach involves checking every possible combination of a buy day and a sell day to see which pair yields the highest gain.

Here's how the algorithm would work step-by-step:

  1. Pick the very first day in your price history as your starting point for buying.
  2. Look at every single day that comes after this chosen day to see what your profit would be if you sold on each of those later days.
  3. Calculate the profit for each of those potential selling days by subtracting your buy price from the sell price.
  4. Keep a mental note of the highest profit you found during this round of comparisons.
  5. Now, move forward to the second day in your history and repeat the whole process by looking at every day after it and calculating potential profits.
  6. Continue this exhaustive process for every single day in the history, always looking ahead to every possible future selling day.
  7. After you have checked every possible pair of buying and selling days, the biggest profit you recorded along the way is your final answer.

Code Implementation

def max_profit_brute_force(stock_prices):
    maximum_profit = 0

    # Iterate through every possible buy day to ensure we test all combinations
    for buy_day_index in range(len(stock_prices)):
        for sell_day_index in range(buy_day_index + 1, len(stock_prices)):
            current_profit = stock_prices[sell_day_index] - stock_prices[buy_day_index]

            # Update the peak profit whenever we discover a higher return
            if current_profit > maximum_profit:
                maximum_profit = current_profit

    # Return the highest accumulated profit found across all pairs
    return maximum_profit

Big(O) Analysis

Time Complexity
O(n²) – For each of the n days in the price history, the algorithm iterates through every subsequent day to calculate potential profits. Specifically, for the first day we check n-1 future selling days, for the second day we check n-2 days, and so on until the final day. This exhaustive pair-checking requires approximately n * n/2 total operations. As the input size n grows, this quadratic workload simplifies to a Big O time complexity of O(n²).
Space Complexity
O(1) – The brute force approach described relies entirely on a few primitive variables, such as a mental note for the highest profit and loop counters to track buying and selling days. No additional dynamic data structures, auxiliary arrays, or recursive call stacks are utilized regardless of the input size N. Therefore, the extra memory consumed remains constant at O(1) extra auxiliary space.

Optimal Solution

Approach

To find the maximum profit from a series of daily prices, the optimal approach tracks the lowest price seen so far while simultaneously calculating the potential profit if we sold on the current day. By walking through the timeline just once and remembering the cheapest cost up to that moment, we can instantly spot the best deal without needing to compare every possible pair of buying and selling days.

Here's how the algorithm would work step-by-step:

  1. Imagine walking forward through a timeline of prices one day at a time, keeping a mental note of the cheapest price you have encountered since the beginning.
  2. As you look at each new price, imagine you decided to sell on that very day, meaning you would have had to buy on the cheapest day you remembered.
  3. Subtract that cheapest past price from today's price to figure out how much profit you would make if you sold right now.
  4. Compare this current potential profit with the record-breaking profit you have saved in your head so far, and update your record if the new one is higher.
  5. Update your mental note of the cheapest price seen so far if today's price happens to be even lower than what you previously recorded.
  6. Continue this process until you reach the end of the timeline, ensuring that your saved record holds the absolute highest profit possible.

Code Implementation

def max_profit(stock_prices):
    if not stock_prices:
        return 0

    # We track the minimum price seen so far to know the best past day to buy.
    lowest_price_so_far = stock_prices[0]

    max_recorded_profit = 0

    for current_price in stock_prices:
        # If we encounter a cheaper buying price, update our baseline.
        if current_price < lowest_price_so_far:
            lowest_price_so_far = current_price

        # Calculate profit for selling today using the cheapest past price.
        current_potential_profit = current_price - lowest_price_so_far

        # Keep track of the highest profit encountered across the timeline.
        if current_potential_profit > max_recorded_profit:
            max_recorded_profit = current_potential_profit

    return max_recorded_profit

Big(O) Analysis

Time Complexity
O(n) – The algorithm iterates through the array of daily prices of size n exactly once from left to right. During this single pass, it performs a constant number of operations per day, such as updating the minimum price and calculating the potential profit. Since the workload scales linearly with the number of input days without any nested loops or repeated scans, the total operations approximate n steps, which simplifies to O(n).
Space Complexity
O(1) – The algorithm only maintains a few primitive scalar variables to track the minimum price seen so far and the maximum profit calculated. These variables consume a constant amount of memory regardless of the input size N of the prices array. Because no dynamic data structures, auxiliary arrays, or recursive calls are utilized, the extra space required does not scale with the length of the input. Thus, the auxiliary space complexity simplifies to O(1) constant space.

Edge Cases

Empty or null input array of prices
How to Handle:
Return zero immediately since no transactions can possibly be made without any days.
Array with only a single element
How to Handle:
Return zero because a stock must be bought and sold on two different days.
Prices in strictly descending order throughout the array
How to Handle:
Track the running minimum price and keep the profit at zero since prices always drop.
Prices in strictly ascending order throughout the array
How to Handle:
Continuously update the minimum price and calculate the maximum difference between the last element and the first.
Array with all identical stock prices
How to Handle:
Keep the maximum profit at zero because buying and selling at the same price yields no gain.
Extremely large arrays with millions of elements
How to Handle:
Use a single-pass O(N) time and O(1) space linear scan to scale efficiently without memory or timeout issues.
Extreme boundary values and large price integers
How to Handle:
Use standard integer types since subtraction of stock prices will not exceed standard integer limits.
0/75 completed