Taro Logo

Best Time to Buy and Sell Stock II

Medium
Asked by:
Profile picture
Profile picture
Profile picture
Profile picture
+25
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
1.5K views
Topics:
ArraysGreedy Algorithms

You are given an integer array prices where prices[i] is the price of a given stock on the ith day.

On each day, you may decide to buy and/or sell the stock. You can only hold at most one share of the stock at any time. However, you can buy it then immediately sell it on the same day.

Find and return the maximum profit you can achieve.

Example 1:

Input: prices = [7,1,5,3,6,4]
Output: 7
Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.
Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
Total profit is 4 + 3 = 7.

Example 2:

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.
Total profit is 4.

Example 3:

Input: prices = [7,6,4,3,1]
Output: 0
Explanation: There is no way to make a positive profit, so we never buy the stock to achieve the maximum profit of 0.

Constraints:

  • 1 <= prices.length <= 3 * 104
  • 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 be returned if the prices array is empty or has only a single element?
  2. Can stock prices be negative or zero, or are they guaranteed to be strictly positive integers?
  3. Are there any transaction fees or limits on the number of transactions we can perform simultaneously (e.g., holding more than one share at a time)?
  4. If the stock prices are strictly decreasing (e.g., [5, 4, 3, 2, 1]), should the function return 0 since no profit can be made?
  5. Can we buy and sell the stock on the exact same day, or is a transaction strictly required to span across at least two distinct days?

Brute Force Solution

Approach

To solve this problem using the brute force approach, you imagine acting out every single possible combination of buying and selling actions over the entire timeline. You test every scenario of when to purchase and when to cash out to see which set of choices yields the absolute highest total profit.

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

  1. Look at the full sequence of price changes from the very beginning to the very end.
  2. Consider the first day and imagine every possible future day you could sell if you bought on this day.
  3. For each of those selling days, calculate the profit you would make and imagine taking that money.
  4. Then, from that selling day onward, repeat the exact same process of choosing another day to buy and another day to sell.
  5. Map out every branching path of buying and selling combinations from start to finish, just like following every possible maze path.
  6. Calculate the total profit accumulated at the end of each complete path.
  7. Compare the totals from every single path you explored and pick the one that gives you the highest amount of money.

Code Implementation

class Solution:
    def maxProfit(self, stock_prices):
        def compute_maximum_profit(current_day, is_currently_holding):
            if current_day >= len(stock_prices):
                return 0
            
            # Explore skipping the current day versus taking action to find all possible paths
            skip_current_day = compute_maximum_profit(current_day + 1, is_currently_holding)
            
            if is_currently_holding:
                sell_stock_profit = stock_prices[current_day] + compute_maximum_profit(current_day + 1, False)
                return max(skip_current_day, sell_stock_profit)
            else:
                buy_stock_profit = -stock_prices[current_day] + compute_maximum_profit(current_day + 1, True)
                return max(skip_current_day, buy_stock_profit)

        # Initiate the recursive exploration from the very beginning with no stock currently held
        return compute_maximum_profit(0, False)

Big(O) Analysis

Time Complexity
O(2^n) – To evaluate every possible combination of buying and selling actions across the n days, the algorithm explores branching paths like a decision tree. At each day in the sequence, the algorithm can choose to buy, sell, or do nothing, which roughly doubles the number of recursive choices at each step. This leads to an exponential growth of operations approximating 2 to the power of n paths, simplifying to an O(2^n) time complexity.
Space Complexity
O(N) – The brute force approach maps out every branching path of buying and selling combinations using a recursive function. As the algorithm explores these choices from the beginning to the end of the timeline, the recursive calls add up to a maximum depth of N, where N is the number of days in the price sequence. Therefore, the extra memory used by the recursion stack grows linearly with the input size N.

Optimal Solution

Approach

Instead of trying to predict the single best time to buy and sell, the optimal strategy captures every single upward movement in price. By collecting every profitable step along the way, you automatically end up with the maximum possible total profit.

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

  1. Observe the price as it changes from one moment to the next.
  2. Whenever you see the price go up from the previous moment, imagine buying right before the rise and selling immediately after.
  3. Collect the profit from that upward movement.
  4. Ignore any moments where the price goes down or stays flat, because you do not want to lose money or waste a transaction.
  5. Continue checking every single price change from start to finish.
  6. Add up all the small profits you collected along the journey.
  7. By grabbing every piece of upward growth, you achieve the ultimate maximum profit without needing to plan complex future trades.

Code Implementation

def max_profit(stock_prices):
    accumulated_profit = 0

    # Iterate through prices starting from the second day to compare with the previous.
    for day_index in range(1, len(stock_prices)):
        current_price = stock_prices[day_index]
        previous_price = stock_prices[day_index - 1]

        # Capture every upward price movement to maximize the total accumulated profit.
        if current_price > previous_price:
            accumulated_profit += current_price - previous_price

    # Return the sum of all collected profitable steps from every upward trend.
    return accumulated_profit

Big(O) Analysis

Time Complexity
O(n) – To capture every single upward price movement, we iterate through the array of length n exactly once to compare each day's price with the previous day's price. At each step, we perform a constant number of operations by checking for a positive price difference and immediately adding it to our total profit. This single-pass approach means the number of operations grows linearly with the size of the input. Therefore, the total operations approximate n steps, which simplifies to O(n).
Space Complexity
O(1) – The algorithm only requires a few primitive variables to track the running sum of profits and the current price comparisons. Because no auxiliary data structures like temporary lists or hash maps scale with the input size N, the memory footprint remains constant. As the number of elements in the price array grows, the extra auxiliary space used does not increase at all. Thus, the auxiliary space complexity simplifies to O(1) constant space.

Edge Cases

Empty or single-element arrays
How to Handle:
Return zero profit immediately because no transaction can be completed without at least two days.
Strictly decreasing prices array
How to Handle:
The greedy accumulation loop adds zero profit because selling on a lower day than buying is never executed.
Strictly increasing prices array
How to Handle:
The algorithm accumulates every positive difference between consecutive days, effectively capturing the total span from start to end.
Array with all identical prices
How to Handle:
All price differences are zero, resulting in a total profit of zero without unnecessary trades.
Prices with consecutive valleys and peaks
How to Handle:
Summing every upward slope correctly captures all local maxima and minima transactions to maximize total profit.
Extremely large arrays approaching maximum memory or time limits
How to Handle:
An O(n) time and O(1) space greedy approach iterates through the array once, scaling efficiently without memory overhead.
Stock prices with zero values
How to Handle:
Since stock prices are non-negative integers, zeros are handled naturally as standard price points without causing arithmetic errors.
Very large integers causing potential overflow
How to Handle:
Using standard 64-bit integers for the profit accumulator prevents overflow issues even with massive price inputs over large datasets.
0/75 completed