Answer to Question #325871 in Python for Vasu

Question #325871

Max Profit

You given a list of prices where prices[i] is the price of a given stock o 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 these is no profit that can be achieved return 0.


Input

The input is a single line containing space seperated integers.


Output

The output should be a single line 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.


Sample Input1

1 2 1 3 6 7 4

Sample Output1

6


1
Expert's answer
2022-04-10T12:36:17-0400
inp = input()
inp = inp.split()
try:
    for i in range(len(inp)):
        inp[i] = int(inp[i])
except Exeption:
    print("Try again!")

buy = float('inf')
sell = float('-inf')
list1 = []
for i in range(len(inp)):
    if inp[i] < buy:
        buy = inp[i]
    for j in range(i + 1, len(inp)):
        if(inp[j] > sell):
            sell = inp[j]
    list1.append(sell - buy)
    
print(max(list1))

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