Python Forum
Any suggestions to improve BuySell stock problem efficiency?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Any suggestions to improve BuySell stock problem efficiency?
#1
I resolved the problem below. It seems this is (O(n)) = n^2.
In case you have a more efficient way to resolve it, kindly let me know. Thanks.
#################################################################################
#Imagine an array of ith element is the price of a given stock on day i.
#If you were only permitted to complete at most one transaction (buy one
# and sell one share of the stock), design an algorithm to find the maximum
#profit. Note that you cannot sell a stock before you buy one. 

#Input: [7,1,5,3,6,4]
#Output:5
#Buy on day 2 (price = 1) and sell on day 5(price = 6), profit = 6-1 =5.
#Not 7-1 = 6, as selling price needs to be larger than buying price.

def BuySell(array):
    
    #Retrieve elements, condition is that buy operation must happen before selling date
    best = 0
    for i in range (len(array)):
        for j in range (len(array)):
            if ( array.index(array[i]) < array.index(array[j]) ):
                profit = abs(   array[i] - array[j]  ) 

                if (array[i] < array[j]):
                   #Retrieve the best profit between buying and selling the stock
                   if (profit > best):
                        best = profit
                        return (f'Buy at ${array[i]}  Sold at ${array[j]}   Profit:${best}')
                        
    return

def main():
    array = [7,1,5,3,6,4]
    print(BuySell(array))

if __name__ == "__main__":
    main()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Logic suggestions for comparing 2 csv's cubangt 7 1,145 Nov-09-2023, 09:54 PM
Last Post: cubangt
  Numpy Structure and Efficiency garynewport 2 696 Oct-19-2022, 10:11 PM
Last Post: paul18fr
  Stock Return calculation problem LFin 10 2,131 Sep-26-2022, 04:28 PM
Last Post: deanhystad
  Efficiency with regard to nested conditionals or and statements Mark17 13 3,186 May-06-2022, 05:16 PM
Last Post: Mark17
  How to use vectorization instead of for loop to improve efficiency in python? PJLEMZ 4 2,428 Feb-06-2021, 09:45 AM
Last Post: paul18fr
  Require Some Suggestions gouravlal 2 1,896 Jul-27-2020, 06:14 AM
Last Post: gouravlal
  Help improve code efficiency benbrown03 9 4,371 Feb-20-2019, 03:45 PM
Last Post: ichabod801
  Python Debugger Suggestions nilamo 3 3,095 Oct-22-2018, 07:05 PM
Last Post: jdjeffers
  Web Scraping efficiency improvement HiImNew 0 2,404 Jun-01-2018, 08:52 PM
Last Post: HiImNew
  Improving Efficiency of SVM by various available kernels Sachtech 0 2,103 Apr-09-2018, 07:29 AM
Last Post: Sachtech

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020