# Function which compute the largest difference in the array between a value and another value with a smaller index # Naive solution using nested loop : O(n) = n*n def maxDiff(source): max = -1000000; # For each item of the array for i in xrange(len(test) - 1, -1, -1): # For each item with smaller index than the current item for j in xrange(i, -1, -1): diff = source[i] - source[j] # If the difference is bigger, then remember if diff > max: max = diff return max # A little bit of testing test = [1, 2, 3, 4, 5, 6] print test print "The maximum difference is: " + str(maxDiff(test)) test2 = [1, 2, 10, 4, 2, -1] print test2 print "The maximum difference is: " + str(maxDiff(test2))
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question