Answer to Question #239207 in Python for sai

Question #239207
You are given a list of prices, where given stack on the i th day.


Write a program to print the maximum profit by choosing a singl to buy a stock and choosing a different day in the future to sell stock.


If there is no profit that can be shieved, return 0
1
Expert's answer
2021-09-19T20:42:23-0400
# Function to find the maximum profit earned by buying and
# selling shares any number of times
def findMaxProfit(price):
 
    # keep track of the maximum profit gained
    profit = 0
 
    # initialize the local minimum to the first element's index
    j = 0
 
    # start from the second element
    for i in range(1, len(price)):
 
        # update the local minimum if a decreasing sequence is found
        if price[i - 1] > price[i]:
            j = i
 
        # sell shares if the current element is the peak, i.e.,
        # (`previous <= current > next`)
        if price[i - 1] <= price[i] and \
                (i + 1 == len(price) or price[i] > price[i + 1]):
            profit += (price[i] - price[j])
            print(f"Buy on day {j + 1} and sell on day {i + 1}")
 
    return profit
 
 
if _name_ == '_main_':
 
    price = [1, 5, 2, 3, 7, 6, 4, 5]
    print("\nTotal profit earned is", findMaxProfit(price))

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS