Skip to main content

Command Palette

Search for a command to run...

[LeetCode] Top Interview 150 Problems Solving # 121 Best Time to Buy and Sell Stock

Updated
2 min read
R

South Korean, master's degree of AI. A research focused AI specialist, and a rogrammer for LLM. I am seeking opportunities worldwide. I used to live in Frankfurt, Moscow, Pretoria, Baguio. Where to next?

Understanding the Problem

It is to find the best time to sell the stock with the max profit. A given list indicates the stock prices. Each element is a stock price in time series. For instance, if prices = [7,1,5,3,6,4], the best time to buy the stock is when the price is 1 and the best time to sell it is when the price is 6, so the profit will be 5, which is a returned number.

Approach

My idea was to loop it twice with for to find the best profit. But I faced the time limit error and could not pass with O(n²). I had to make it to O(n).

Solution

Well, my goal was to find the min number and the max difference to find the best profit. So first initialize min_num with float(“inf”). The code will start the loop one by one of the prices.

If the element p is lower than min_num, set p to min_num for subtraction comparison. if p - min_num is greater than max_diff, which means the profit is greater, set max_diff with p - min_num.

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_num = float("inf")
        max_diff = 0

        for p in prices:
            if p < min_num:
                min_num = p
            elif p - min_num > max_diff:
                max_diff = p - min_num
        return max_diff

Reflection

The code was simple but it took some time for me to solve the problem. I was busy visiting my parents and I was looking for other jobs to move to, which means I could not focus on the problem solving algorithm. Anyways, time efficiency this time again.

More from this blog

R

Ramieeee's IT blog

36 posts

Algorithms, IT news, my thoughts note