Notice: Undefined offset: 6902316 in /var/www/html/qa-external/qa-external-users.php on line 744
Can someone explain what this code does? - OnlineGDB Q&A
Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Can someone explain what this code does?

+10 votes
asked Mar 1, 2025 by (6,150 points)

I recently started taking python ds&a seriously. There is one problem tho, the website mentions a code, which it does explain but not really that good.

def best_profit(prices):
    n = len(prices)
    best = 0
    min_price = prices[0]
    for i in range(n):
        min_price = min(min_price, prices[i])
        best = max(best, prices[i] - min_price)
    return best

Apparently, if we have a table of days and prices (different price for each day) then this program will calculate the best day to buy and to sell, and also the profit. The only part of the code I understand is how it calculates the profit.

I am really sorry if I asked a really simple question, I am not the smartest guy and my logical thinking skills are basically underground level.

1 Answer

+2 votes
answered Mar 3, 2025 by Peter Minarik (101,420 points)
selected Mar 4, 2025 by
 
Best answer
1: def best_profit(prices):
2:    n = len(prices)
3:    best = 0
4:    min_price = prices[0]
5:    for i in range(n):
6:        min_price = min(min_price, prices[i])
7:        best = max(best, prices[i] - min_price)
8:    return best

Line 1: define a function called best_profit. It expects an argument that is a list of prices

Line 2: let n store the values of the number of prices (days) received in the argument

Line 3: Let's assume the best profit is 0 (we can only get better than this)

Line 4: Let's assume the minimum price is the first one in the prices list

Line 5: Let's iterate through all the prices, as established before, we have n prices (days) in our list

Line 6: The minimum price (min_price) is either the old min_price, or the currently iterated price (price[i]), whichever is smaller.

Line 7: the best profit is the maximum of the best profit so far or the price difference between the currently iterated price and the minimum price (min_price) so far.

Line 8: return the best price.

Note: I do not believe this function works correctly though since the min_price changes throughout the loops and it may not have found the correct value yet when the best profit is calculated.

I've implemented my own solution for the problem and called in best_profit2. See the comparison of the two functions below:

import sys

def best_profit(prices):
    n = len(prices)
    best = 0
    min_price = prices[0]
    for i in range(n):
        min_price = min(min_price, prices[i])
        best = max(best, prices[i] - min_price)
    return best

def best_profit2(prices):
    min_price = sys.maxsize
    max_price = 0
    for price in prices:
        if price < min_price:
            min_price = price
        if price > max_price:
            max_price = price
    
    return max_price - min_price

priceList = [2, 4, 6, 8, 9, 7, 5, 3, 1]

print(best_profit(priceList))
print(best_profit2(priceList))
commented Mar 4, 2025 by (6,150 points)
Thank you, you are really helpful! Even taking the time to implement your own solution. If i am being completely honest, I think your solution is more understandable.
commented Mar 4, 2025 by Peter Minarik (101,420 points)
I'm happy to help.

Keep on learning. :)
commented Mar 4, 2025 by Juan Miguel Soto Zeevaert (100 points)
That good however there a little mistake in your solution btw : you're taking the overall maximum and minimum of the list of prices so the second solution is not exactly right if you take into account that the minimum price MUST be ahead in the list compared to the maximum (bc it's not possible that you buy something but have already sold it three days ago altough you hadn't bought at that time : so the second solution doesn't take into account those scenarios as they are impossible).
commented Mar 4, 2025 by Juan Miguel Soto Zeevaert (100 points)
If you want a solution that would fit your reasoning it would better be :

def best_profit2(prices):
    min_price = float('inf') #that's the same as the statement that you used before but that's more intuitive to me
    max_price = 0
    max_profit = 0

    profit = 0

    for price in prices:
        if price < min_price:
            # keep track of the better profit
            max_profit = max(max_profit, profit)
            
            min_price = price
            # reset the max_price because it you can't sold it before you've bought it
            max_price = price
            
        if price > max_price:
            max_price = price

        profit = max_price - min_price


    return max_profit
commented Mar 4, 2025 by Juan Miguel Soto Zeevaert (100 points)
But I think that the first version was better but we can hone it a bit by doing this:

def best_profit(prices):
    best = 0
    min_price = prices[0]
    for price in prices:
        min_price = min(min_price, price)
        best = max(best, price - min_price)
    return best

It a little less intuitive to understand and a bit trickier to read but
If you want to use the morse operator it can become:

def best_profit(prices):
    best = 0
    min_price = prices[0]
    for price in prices:
        best = max(best, price - (min_price := min(min_price, price)))
    return best
commented Mar 5, 2025 by Peter Minarik (101,420 points)
# reset the max_price because it you can't sold it before you've bought it

Not true if you're talking about the stock exchange. :)

You can actually sell things you do not own in hopes that the future price of the commodity will fall and you can buy it later for a lower price so you can make a profit.

https://en.wikipedia.org/wiki/Short_(finance)

But you're right, if it's good old-fashioned selling things on the physical market, you usually cannot sell what you do not own. You need the stock exchange, then you can set the whole world upside down. :D
commented Mar 6, 2025 by Juan Miguel Soto Zeevaert (100 points)
You're right I would have had to precise further more
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and receive answers from other members of the community.
...