Python Array Indexing, How else can I approach the challenge below?

Viewed 43

I'm trying to solve python challenges however I'm stuck with the on below. I've put the decription of the challenge. My code gives me the difference between the largest and smallest items in the array, this is not what I want. I'm trying to get the difference between item 24 and item 40 without hard coding it.

I appreciate any help.

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.

def ArrayChallenge(arr):

low = 0
diff = 0

for number in range (0, len(arr)):
    print("Current number", number)
    low = arr[number]
    
    for stock  in arr:
        print("stock", stock)

        if (low < stock):
            diff = stock - low
            print("low", low)
            print("diff", diff)
        elif (low > stock):
            if diff == 0:
                diff = -1
            else:
                pass
            print("low", low)
            print("diff", diff)
        else:
            if diff == 0:
                diff = -1
            else:
                pass
            print("low", low)
            print("diff", diff)

            print("\n\n")

oldChalengeToken = "8nqu3wv71e9"
challengeToken = oldChalengeToken[::-1]
answer = diff, ":", challengeToken

return answer
0 Answers
Related