DEV Community

Justin Bermudez
Justin Bermudez

Posted on

Leetcode: Best Time to Buy and Sell Stocks II Python Solution With Explanation

Link to leetcode question.

Full Solution

def maxProfit(self, prices: List[int]) -> int:
    if not prices or len(prices) is 1:
        return 0
    profit = 0
    for i in range(1, len(prices)):
        if prices[i] > prices[i - 1]
    return profit

Edge Cases

if not prices or len(prices) is 1:
    return 0

We need to check if anything is in the input. If nothing is in the input or if there is only one item in there, then we cannot make any profits. Therefore, we would return 0.

Keeping Track of our Results

profit = 0
This should be pretty self explanatory where we would keep track of what we want to return at the end.

Going Through the Input

for i in range(1, len(prices)):
You can do this part in many ways, but the way I solved this was iterating the input array starting from the second index so we can compare the current to the previous.
If we compared the current to the previous and started at the beginning of the array, then we would hit an error.

if prices[i] > prices[i - 1]:
    profit += prices[i] - prices[i - 1]

So if our current price is greater than the previous stock, then that means we will make a profit which is what we want. So we will add to our profit the difference between our current stock price and the stock price before it.

If the price of the stock is smaller than the previous stock price, then we will not make a profit so we will continue iterating through the input array.

Finally we can return the resulting profit.

Top comments (0)