Answer to Question #266870 in Python for kaavya

Question #266870

Profit Trade:



You are given a list of prices, where prices[i] is the price of the given stock on the i th day. Write a program to print the maximum profit by choosing a single day to buy a stock and choosing a different day in the future to sell that stock. If there is no profit that can be achieved, return 0.



Input:



The input should be a single line containing space-separated integers.



Output:



The output should be a integer.



Explanation:



In the example, the given prices are 7,1,5,3,6,4



Buying stocks on day two having price 1 and selling them on the fifth day having price 6 would give the maximum profit which is 6-1



So the output should be 5.

1
Expert's answer
2021-11-16T07:44:45-0500

def stockBuy_Sell(price, n):

   

  #For calculating prices msut be given at least for 2 days

  if (n == 1):

    return

   

  # Traverse through given price array

  i = 0

  while (i < (n - 1)):

     

    #here we compare the current answer with previous one

    while ((i < (n - 1)) and

        (price[i + 1] <= price[i])):

      i += 1

     

    # If we reached the end, break

    # as no further solution possible

    if (i == n - 1):

      break

     

    # Store the index of minima

    buy = i

    i += 1

     

    # Find Local Maxima

    # Note that the limit is (n-1) as we are

    # comparing to previous element

    while ((i < n) and (price[i] >= price[i - 1])):

      i += 1

       

    # Store the index of maxima

    sell = i - 1

     

    print("Buy on day: ",buy,"\t",

        "Sell on day: ",sell)

     

# Driver code

 

# Stock prices on consecutive days

price = [7,1,5,3,6,4]

n = len(price)

 

# Function call

stockBuy_Sell(price, n)


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