Problem Statement
You're given a list of stock prices over a period of time. Your goal is to write a Python function that calculates the maximum profit you could have made by buying and selling the stock at the right times.
Input list : [9, 1, 3, 6, 4, 8, 3, 5, 5]
Expected Output : 7
Explanation: Buy on day 2 (price = 1) and sell on day 6 (price = 8), profit = 8 - 1 = 7.
NOTE : GIVE IT A TRY BEFORE MOVING TO THE SOLUTION.
Initialization
prices = [9, 1, 3, 6, 4, 8, 3, 5, 5]: This initializes a list prices containing stock prices.
pl = []: This initializes an empty list pl to store profits.
While Loop
while prices:: This loop iterates until there are elements in the prices list.
Finding Minimum and Maximum Prices
min_ind = prices.index(min(prices)): This finds the index of the minimum price in the prices list.
min_price = prices[min_ind]: This gets the minimum price using the index found.
max_price = max(prices[min_ind:]): This finds the maximum price from the remaining list after the minimum price index.
Profit Calculation and Update
if max_price <= min_price:: This condition checks if it's not possible to make a profit (i.e., maximum price is less than or equal to minimum price).
prices.remove(min_price): If there's no profit to be made, it removes the minimum price from the list.
else:: If there's potential profit to be made:
pl.append(max_price - min_price): Calculates and appends the profit to the pl list. However, the profit is appended twice here (unnecessary duplication).
prices.remove(min_price): Removes the minimum price from the list.
Printing Maximum Profit
print(max(pl)): Prints the maximum profit stored in the pl list after all iterations.
Complete Code
prices = [9, 1, 3, 6, 4, 8, 3, 5, 5]
pl=[]
while prices:
min_ind=prices.index(min(prices))
min_price=prices[min_ind]
max_price=max(prices[min_ind:])
if max_price<=min_price:
prices.remove(min_price)
else:
pl.append(max_price-min_price)
pl.append(max_price-min_price)
prices.remove(min_price)
print(max(pl))
Thankyou, If you have any better solution please post in the comment box below.
Comments