If you have any query feel free to chat us!
Happy Coding! Happy Learning!
Lecture 100:- Buy & Sell Stocks
To maximize profit by buying and selling stocks, you can use a simple algorithm that traverses the list of stock prices and keeps track of the minimum price seen so far and the maximum profit that can be obtained by selling at the current price. Here's a Python function that implements this algorithm:
pythonCopy code
def max_profit(prices): if not prices or len(prices) < 2: return 0 min_price = prices[0] max_profit = 0 for price in prices[1:]: max_profit = max(max_profit, price - min_price) min_price = min(min_price, price) return max_profit # Test the function stock_prices = [7, 1, 5, 3, 6, 4] print(max_profit(stock_prices)) # Output: 5 (Buy at 1, sell at 6) stock_prices = [7, 6, 4, 3, 1] print(max_profit(stock_prices)) # Output: 0 (No profitable trade possible)
In this code, the
max_profit()
function takes a list of stock prices as input. It initializes variablesmin_price
to the first price in the list andmax_profit
to 0. Then, it iterates through the rest of the prices. For each price, it updatesmin_price
to the minimum of the current price and the previously seen minimum. It also updatesmax_profit
to the maximum of the current profit and the difference between the current price and the minimum price seen so far.The final result will be the maximum profit that can be obtained from the given list of stock prices by buying at a lower price and selling at a higher price. The algorithm runs in O(n) time complexity, where n is the number of elements in the list of stock prices.
Comments: 2
SCIAKU Team please upload 1st video of TREE please please please, please
I bought this course, it worth it!
Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it
Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website