 # DCP47 - Company's Stock Prices

Oct 20th, 2020
1,082
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. '''
3. Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates
4. the maximum profit you could have made from buying and selling that stock once. You must buy before you can sell it.
5. 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.
6. '''
7. from random import randrange
8.
9. def solve(array):
10.     n = len(array)
11.     if n <= 1:
12.         return "The given array (" + str(array) + ") has length = " + str(n) + ", so I cannot find 2 numbers"
13.     maxProfit = array - array
14.     bigIndex = 0
15.     smallIndex = 1
16.     # So, I try to find 2 numbers big and small with these characteristics:
17.     # 1) big is right og small element in the given array
18.     # 2) The difference big - small be the maximum possible
19.     for i in range(0, n-1):
20.         for j in range(i, n):
21.             profit = array[j] - array[i]
22.             if profit > maxProfit:
23.                 maxProfit = profit
24.                 bigIndex = j
25.                 smallIndex = i
26.     return maxProfit, array[bigIndex], array[smallIndex]
27.
28.
29. def prettyPrint(array):
30.     maxProfit, big, small = solve(array)
31.     print(str(array) + " ----> Max profit = " + str(big) + " - " + str(small) + " = " + str(maxProfit))
32.
33. # MAIN FUNCTION
34. array1 = [9, 11, 8, 5, 7, 10]
35. array2 = [10, 7, 1, 6, 12, 4]
36. array3 = [randrange(20) + 1 for i in range(8)]
37. array4 = [randrange(100) + 1 for i in range(10)]
38. prettyPrint(array1)
39. prettyPrint(array2)
40. prettyPrint(array3)
41. prettyPrint(array4)
RAW Paste Data