Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- '''
- This problem was asked by Facebook.
- Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates
- the maximum profit you could have made from buying and selling that stock once. You must buy before you can sell it.
- For example, given [9, 11, 8, 5, 7, 10], you should return 5, since you could buy the stock at 5 dollars and sell it at 10 dollars.
- '''
- from random import randrange
- def solve(array):
- n = len(array)
- if n <= 1:
- return "The given array (" + str(array) + ") has length = " + str(n) + ", so I cannot find 2 numbers"
- maxProfit = array[0] - array[1]
- bigIndex = 0
- smallIndex = 1
- # So, I try to find 2 numbers big and small with these characteristics:
- # 1) big is right og small element in the given array
- # 2) The difference big - small be the maximum possible
- for i in range(0, n-1):
- for j in range(i, n):
- profit = array[j] - array[i]
- if profit > maxProfit:
- maxProfit = profit
- bigIndex = j
- smallIndex = i
- return maxProfit, array[bigIndex], array[smallIndex]
- def prettyPrint(array):
- maxProfit, big, small = solve(array)
- print(str(array) + " ----> Max profit = " + str(big) + " - " + str(small) + " = " + str(maxProfit))
- # MAIN FUNCTION
- array1 = [9, 11, 8, 5, 7, 10]
- array2 = [10, 7, 1, 6, 12, 4]
- array3 = [randrange(20) + 1 for i in range(8)]
- array4 = [randrange(100) + 1 for i in range(10)]
- prettyPrint(array1)
- prettyPrint(array2)
- prettyPrint(array3)
- prettyPrint(array4)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement