Skip to content

Instantly share code, notes, and snippets.

@oskar-j
Last active August 29, 2015 14:25
Show Gist options
  • Save oskar-j/8b99729826a1f4242e70 to your computer and use it in GitHub Desktop.
Save oskar-j/8b99729826a1f4242e70 to your computer and use it in GitHub Desktop.
Find the monotonic pair whose indices are the furthest apart in Python
# method helps with fact that enumerate from reversed
# won't yield reversed indexes
def reverse_enum(L):
# guaranteed to NOT make any extra copy or search operations, O(1)
for index in reversed(xrange(len(L))):
yield index, L[index]
def solution(A):
top = list()
maximum = float("-inf")
# allocate temp list with O(n) time, put there maximal values descending
for item in reversed(A):
if (item > maximum):
maximum = item
top.insert(0, maximum)
best = 0
cur_max_index = 0
# iterate with O(n) time
for i, item in enumerate(A):
# simply calculate the distance, takes O(c*n) time, c between 0 and 1
while(cur_max_index < len(top) and top[cur_max_index] >= item):
cur_max_index += 1
if((cur_max_index - 1 - i) > best):
best = cur_max_index - 1 - i
return best
print solution([0])
print solution([0, 0])
print solution([1, 3, -3])
print solution([5, 3, 6, 3, 4, 2])
@oskar-j
Copy link
Author

oskar-j commented Jul 21, 2015

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment