Created
April 8, 2022 05:41
-
-
Save thekhairul/f5860bf129b94faad759489614cbcf4c to your computer and use it in GitHub Desktop.
InterviewBit - max distance between indices of an integer array (Python)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def maximumGap(self, A): | |
# step 0: make a list of touples (value, index) and sort it by value (O(nlogn)) | |
sortedA = sorted(((v, i) for i, v in enumerate(A))) | |
# step 1: init maxGap to store maximum gap between 2 indices | |
# and minNum to store the minimum index so far in the loop | |
maxGap = 0 | |
minNum = sortedA[0][1] | |
#step 2: loop through sortedA to find maximum index gap (O(n)) | |
for i in range(1,len(sortedA)): | |
if sortedA[i][1] < minNum: | |
minNum = sortedA[i][1] | |
else: | |
maxGap = max(maxGap, sortedA[i][1] - minNum) # O(n) | |
return maxGap |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment