Answer to Question #240521 in Python for sai krishna

Question #240521

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 an 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 input 1

7 1 5 3 6 4

sample output 1

5

sample input 2

1 11 13 21 19

sample output 2

20


1
Expert's answer
2021-09-22T23:49:25-0400
def maxDifference(arr, n):
	max_diff = arr[1] - arr[0]
	min_el = arr[0]
	
	for i in range( 1, n ):
		if (arr[i] - min_el > max_diff):
			max_diff = arr[i] - min_el
	
		if (arr[i] < min_el):
			min_el = arr[i]
	return max_diff
	
# arr = [7,1,5,3,6,4]
arr = [1,11,13,21,19]
size = len(arr)
print (maxDifference(arr, size))

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