Buy & Sell Stocks

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

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 variables min_price to the first price in the list and max_profit to 0. Then, it iterates through the rest of the prices. For each price, it updates min_price to the minimum of the current price and the previously seen minimum. It also updates max_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.

14. Week7 - Assignments

Comments: 2

profile
@mk.info.work
17-Feb-2024, 10:20 PM

SCIAKU Team please upload 1st video of TREE please please please, please

profile
@na3744
23-Feb-2024, 02:52 AM

I bought this course, it worth it!

profile
@mk.info.work
15-Nov-2023, 10:25 PM

Hi i want to buy this course but you dont have master card payment method please let me know how i can buy it

profile
@sciaku1
11-Jan-2024, 03:23 PM

Dear mk.info.work, Now we have all types of payment options. If you need to purchase just checkout our official website

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?