Skip to content

Instantly share code, notes, and snippets.

@MUWASEC
Last active November 19, 2022 00:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MUWASEC/ac358ee4047b72bd8ebd9e265d77de91 to your computer and use it in GitHub Desktop.
Save MUWASEC/ac358ee4047b72bd8ebd9e265d77de91 to your computer and use it in GitHub Desktop.
stock picker ?
'''
CoderByte: Array Challenge
Have the function ArrayChallenge(arr) take the array of numbers stored in arr which will contain integers that represent the amount in dollars that a single stock is worth, and return the maximum profit that could have been made by buying stock on day x and selling stock on day y where y > x. For example: if arr is [44, 30, 24, 32, 35, 30, 40, 38, 15] then your program should return 16 because at index 2 the stock was worth $24 and at index 6 the stock was then worth $40, so if you bought the stock at 24 and sold it at 40, you would have made a profit of $16, which is the maximum profit that could have been made with this list of stock prices.
If there is not profit that could have been made with the stock prices, then your program should return -1. For example: arr is [10, 9, 8, 2] then your program should return -1.
Examples
Input: [10,12,4,5,9]
Output: 5
Input: [14,20,4,12,5,11]
Output: 8
Input: [1,10]
Output: 9
Input: [1,2,3,4,5]
Output: 4
'''
def ArrayChallenge(arr):
# code goes here
# get lower stock
sort_stock = sorted(arr)
low=arr[0]
for i in range(arr.index(sort_stock[-1])+1, len(arr)):
if arr[i]>low:
break
low=arr[i]
# get higher stock
stock=sorted([arr[i] for i in range(arr.index(low)+1, len(arr))])
try:
high=stock[-1]
except:
return -1
print(f'low {low}|{high}')
# this will remove all duplicate stock and choose the second duplicate stock
if low>stock[0] and low in stock:
low=stock[0]
print(f'low {low}|{high}')
if high-low < 1:
return -1
else:
return high-low
# keep this function call here
print(ArrayChallenge([44, 30, 24, 32, 35, 30, 40, 38, 15]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment