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 buyPrice = arr[i] sellPrice = arr[j] print ("highestProfit=", highestProfit, "buyPrice=", buyPrice, "sellPrice=", sellPrice)
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.
Good answer myk.
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.
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 buy = None sell = 0 while scenarios > 0: print("Running Scenario " + str(scenario) + "...") for price in prices: buy = prices[index] if prices[index + 1] > prices[index]: sell = prices[index + 1] else: index = index + 1 continue print(buy) print(sell) profit = sell - buy print(profit) scenarios = scenarios - 1 scenario = scenario + 1 index = 0 index = index + 1