DEV Community

Cover image for LeetCode Challenge: Best Time to Buy and Sell Stock II
Bharath Sriraam R R
Bharath Sriraam R R

Posted on • Updated on

LeetCode Challenge: Best Time to Buy and Sell Stock II

This is one of those problems which when you solve, you take a small step towards going to the next level.

Problem

Say you have an array prices for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).

Note:
You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).

Example 1:

Input: [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.

Example 2:

Input: [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.
             Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are engaging multiple transactions at the same time. You must sell before buying again.

Example 3:

Input: [7,6,4,3,1]
Output: 0
Explanation: In this case, no transaction is done, i.e. max profit = 0.

Initial thoughts

Since it's a real situation there's no need to find a realistically close situation and simulate it.

If you try observing what you would do in real life it's simple to notice the steps and write an efficient algorithm.

However if unfortunately, you're unable to do so then you would probably try all possible combinations of trades and find the combo with the maximum profit. This is what approach 1 is about.

Approach 1

The goal is to recursively calculate max profit possible for trades starting from all possible indices.

Algorithm:

  1. Define the recursive function nextMaxProfit with parameters: prices which is the array and today which is the starting index from which the function will calculate the max profit.
  2. The stopping condition or base case for the recursion is if the today param is out of bounds.
  3. Initialize totalMax to store the max profit for trades starting from today.
  4. Iterate variable start from today till the end of prices
  5. Initialize maxprofit to zero in each iteration of step 4
  6. Iterate from start+1 till the end of the array and if current price is greater than prices[start] then recalculate maxprofit
  7. After the end of step 6 recalculate totalMax
  8. Return totalMax

Code:

def approach1(prices):
    return nextMaxProfit(prices, 0)


def nextMaxProfit(prices, today):

    if (today >= len(prices)):
        return 0

    totalMax = 0
    for start in range(today, len(prices)):
        maxprofit = 0
        for i in range(start+1, len(prices)):
            if (prices[i] > prices[start]):
                profit = nextMaxProfit(prices, i + 1) + prices[i] - prices[start]
                if (profit > maxprofit):
                    maxprofit = profit

        if (maxprofit > totalMax):
            totalMax = maxprofit

    return totalMax

Complexity analysis:

Time complexity: O(n^n)
Space complexity: O(n)

Approach 2

Ask yourself

What would I do in real life, if I was given this situation?

You'd think something like:

  1. I'll buy the first day's stock
  2. If the next day's price is not decreasing then wait
  3. The moment it goes down then I sell and buy the current stock and repeat

And it makes sense because you're assuming you have an infinite budget which works for this question.

Since that covered the algorithm let's look at the code.

Code:

def approach2(prices):
    if len(prices) == 0:
            return 0

    ans = 0
    buy = prices[0]
    sell = prices[0]

    for i in range(1, len(prices)):
        if prices[i] < sell:
            ans += sell - buy
            buy = prices[i]

        sell = prices[i]

    ans += sell - buy
    return ans

Complexity analysis:

Time complexity: O(n)
Space complexity: O(1)

Summary

There are many variants of this that you can try on LeetCode if you're interested.

Here's the replit

Top comments (0)