DEV Community

Justin Bermudez
Justin Bermudez

Posted on

2 1

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.

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay