LeetCode Challenge: Best Time to Buy and Sell Stock II
Tags: computerscience, beginners, leetcode, problemsolving
Published: 2020-04-13 21:33:43

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:__
```python
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:__
```python
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
{% replit @13point5/Best-Time-to-Buy-and-Sell-Stock-II %}