# Assignment for Max Stock Profit

``````arr = [2,5,1.3,4,5,7,8,2,1,1.5,2,6,7.3,1,6,7.2,4,2,1,3.3]

highestProfit = -1
for i in range(0 ,len(arr)):
for j in range (i,len(arr)):
profit = arr[j] - arr[i]
if profit > highestProfit:
highestProfit = profit
sellPrice = arr[j]

Great!
Can you make it more efficient?

Tried with a sorted array and looked at diff of highest and lowest value and then looked the index of the highest is higher than the lowest , but found thats an incorrect logic!

Can you give a hint?

I think this works:

``max([arr[i]-min(arr[:i]) for i in range(1,len(arr))])``

Yes, it gives the value as 7, which in this case is the highest profit!
Can you explain what the code is doing? I understand the for loop, but not the precursor to it!
How is it ensuring that the buyPrice come first followed by the sellPrice.

But doing you the complexity of this one? It is still O(n^2). In super simple words, complexity represents the how many steps will a program take to process n records.

Here for every element we are finding the delta with the minimum of all of the element which is going to be n*n times.

@sgiri:
Can you please provide feedback on the following code:
‘’’
You are given stock values in an array (365 values) of one year:
[1, 3, 1.5, 6, 7…]
You can only buy once and then sell
You need to find the max profit that you can make
‘’’

``````prices = [1,3,1.5,6,7]
scenarios = len(prices)
scenario = 1
index = 0
sell = 0
while scenarios > 0:
print("Running Scenario " + str(scenario) + "...")
for price in prices:
if prices[index + 1] > prices[index]:
sell = prices[index + 1]
else:
index = index + 1
continue

print(sell)
print(profit)
scenarios = scenarios - 1
scenario = scenario + 1
index = 0
index = index + 1``````

What is the complexity of this?