In: Computer Science
Please write simple python program with explanation
Problem statement:
Stock markets are venues where buyers and sellers of shares meet and decide on a price to trade.Eddard is very interested in trading in stock market and he started gathering information of one stock.He has projected market prices for that share over the next n months.Eddard wants to purchase and resell the share to earn profits.He is much worried about the loss that might occur so he wanted to calculate "Minimum loss" according to following rules :
1.The share cannot be sold at a price greater than or equal to the price it was purchased at(i.e. it must be resold at a loss).
2.The share cannot be resold within the same month it was purchased.
Find and print the minimum amount of money Eddard must lose if he buys the share and resells it within the next n months.
Input Format:
The first line contains an integer n,denoting the number of months of share data.
The second line contains n space separated long integers describing the respective values of p1,p2,...pn.
Constraints:
1<=n<=10^5
1<=pi<=10^16
All the market prices are distinct and valid answer exists.
Output Format:
Print a single integer denoting the minimum amount of money Eddard must lose if he buys the share and resells it within the next n months.
Sample Input1:
3
5 10 3
Sample Output1:
2
Explanation:
Eddard buys the stock in month1 at price p1=5 and sells it in month 3 at p3 for a minimal loss of 5-3 = 2 .
Sample Output2:
5
77 82 76 88 80
Sample Output2:
1
n = int(input()) #taking input of number of month
stocks= list(map(int, input().split())) #storing the stock price of each month in list
diff = [] #declaring list to store the difference
for i in range(len(stocks)-1): #Outer for loop for initial stocks
for j in range(len(stocks)-1,i,-1): #Inner for loop for later stocks
if(stocks[i]>stocks[j]): #Condition for the price of stock of next month to be less than the current month
diff.append(stocks[i]-stocks[j]) #Calculating the difference between current month's and later month's stock price and appending it to list diff
if(len(diff)==0): #Checking for situation in which stock price didn't decrease in the next month
print("Stock can't be sold as there's no month in which stock's price is decreasing")
else:
print(min(diff)) #Printing the minimum value of the list diff in order to determine the minimum loss
Screen shot of code and output:
Explanation: