Day 5: Best Time to Buy and Sell Stock – My Leetcode Journey

Brad Malgas
Author
Failed to solve the problem with an O(N²) approach, then learned a simpler O(N) solution from the community. A humbling but valuable experience.
At this point, I’ve accepted that I won’t have time every single day to tackle a question. It was a nice idea, but I need to stretch the timeframe. My main goal is learning, not cramming for an interview or showing off the number of questions I’ve solved. I’d rather take my time and focus on retention.
That said, today’s problem was 121. Best Time to Buy and Sell Stock (or as I like to call it: Bitcoin in 2018).
My notes were:
- No negatives—return 0 if there’s no profit.
- Look for the largest difference, with a check that it’s greater than 0.
My first solution used a double for loop (never a good sign). For each day’s price, I compared it against all subsequent days to see if profit was possible.
This was way too slow and didn’t even pass the test cases. It was an O(N²) solution, so I knew I needed to find an O(N) approach.
I tried a few single-pass solutions, but they all failed due to constraints:
- The optimal buy price isn’t always the smallest value.
- The optimal sell price isn’t always the largest value.
- The best difference could appear at the beginning or the end.
After an hour, I gave up and looked at solutions. It was frustrating—it was the first time I completely failed a problem. But I reminded myself: failure is part of the process.
The solution I found on AlgoMap.io was outdated. I had been overcomplicating things by tracking three variables (buyPrice, sellPrice, maxProfit). The most intuitive solution I found was this one:
Leetcode Solution Link
It wasn’t my own, but it was clear and easy to follow, so I recreated it in Python and credited the source.
My solution can be found on my GitHub: 121. Best Time to Buy and Sell Stock.py
Loading reactions…
Loading comments…