Find max in-order difference in array











up vote
1
down vote

favorite












Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].



If there is no solution possible, return 0.



Example :



A : [3 5 4 2]



Output : 2
for the pair (3, 4)



My Code :



def maximumGap(self, A):
if len(A)==1: return 0
a_list = sorted(([Val,indeX] for indeX,Val in enumerate(A)), reverse=True)

rest = [indeX for val,indeX in a_list] # rest stores all the index from a_list which is sorted in decreasing order
len_rest = len(rest)
del a_list[:]
results =

for i in range(len_rest):
if i != len_rest-1:
results.append(rest[i] - min(rest[i+1:]))
else: continue

ans = max(results)
if ans < 0: return 0
else: return ans


Sample input taken for explanation:



A = [34, 8, 10, 3, 2, 80, 30, 33, 1]


Brief summary of my algorithm:



1. a_list is a list of lists which will store all the numbers from the orginal list (list A) in sorted order along with their indexes.



`a_list = [[80, 5], [34, 0], [33, 7], [30, 6], [10, 2], [8, 1], [3, 3], [2, 4], [1, 8]]`


2. rest is a list which will store all the indexes from a_list.



`rest = [5, 0, 7, 6, 2, 1, 3, 4, 8]`


(After this, a_list is deleted to empty the space)



3. Now, the crux of the logic is:
Since list is sorted in descending order, I need not take care of the constraint: A[i] <= A[j]



I will just iterate the list: rest and in each iteration, say 0th iteration, rest[0] = 5 is subtracted from the smallest remaining elements in list: rest



Each result of the iteration is stored in list: results



4. results = [5, -1, 6, 5, 1, -2, -1, -4]



5. Max of list results will give me the answer.



(It is important to note that while sorting the list we must also store the original index of the values instead of blindly sorting it.)



Now, coming to the actual problem:



On submitting my solution at interviewbit website, my code is giving correct answers to all test cases but time limit is exceeded



I am not able to figure out what how to optimise this further.



Time complexity of my code,correct me if i am wrong, is O(N log N)



Sorting takes O(N log N) time in the worst case when using sort function in python.



My main question is how to optimise this code further?



Found on www.interviewbit.com










share|improve this question
























  • Your indentation seems to be off. The method inside the class should not be on the same level as the class
    – Graipher
    Nov 25 '16 at 13:01






  • 1




    there is a solution in a o(N) complexity: see, you only have to keep track of the lowest value seen yet and compute the difference between the current point and the lowest value seen yet
    – JMat
    Nov 25 '16 at 16:19















up vote
1
down vote

favorite












Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].



If there is no solution possible, return 0.



Example :



A : [3 5 4 2]



Output : 2
for the pair (3, 4)



My Code :



def maximumGap(self, A):
if len(A)==1: return 0
a_list = sorted(([Val,indeX] for indeX,Val in enumerate(A)), reverse=True)

rest = [indeX for val,indeX in a_list] # rest stores all the index from a_list which is sorted in decreasing order
len_rest = len(rest)
del a_list[:]
results =

for i in range(len_rest):
if i != len_rest-1:
results.append(rest[i] - min(rest[i+1:]))
else: continue

ans = max(results)
if ans < 0: return 0
else: return ans


Sample input taken for explanation:



A = [34, 8, 10, 3, 2, 80, 30, 33, 1]


Brief summary of my algorithm:



1. a_list is a list of lists which will store all the numbers from the orginal list (list A) in sorted order along with their indexes.



`a_list = [[80, 5], [34, 0], [33, 7], [30, 6], [10, 2], [8, 1], [3, 3], [2, 4], [1, 8]]`


2. rest is a list which will store all the indexes from a_list.



`rest = [5, 0, 7, 6, 2, 1, 3, 4, 8]`


(After this, a_list is deleted to empty the space)



3. Now, the crux of the logic is:
Since list is sorted in descending order, I need not take care of the constraint: A[i] <= A[j]



I will just iterate the list: rest and in each iteration, say 0th iteration, rest[0] = 5 is subtracted from the smallest remaining elements in list: rest



Each result of the iteration is stored in list: results



4. results = [5, -1, 6, 5, 1, -2, -1, -4]



5. Max of list results will give me the answer.



(It is important to note that while sorting the list we must also store the original index of the values instead of blindly sorting it.)



Now, coming to the actual problem:



On submitting my solution at interviewbit website, my code is giving correct answers to all test cases but time limit is exceeded



I am not able to figure out what how to optimise this further.



Time complexity of my code,correct me if i am wrong, is O(N log N)



Sorting takes O(N log N) time in the worst case when using sort function in python.



My main question is how to optimise this code further?



Found on www.interviewbit.com










share|improve this question
























  • Your indentation seems to be off. The method inside the class should not be on the same level as the class
    – Graipher
    Nov 25 '16 at 13:01






  • 1




    there is a solution in a o(N) complexity: see, you only have to keep track of the lowest value seen yet and compute the difference between the current point and the lowest value seen yet
    – JMat
    Nov 25 '16 at 16:19













up vote
1
down vote

favorite









up vote
1
down vote

favorite











Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].



If there is no solution possible, return 0.



Example :



A : [3 5 4 2]



Output : 2
for the pair (3, 4)



My Code :



def maximumGap(self, A):
if len(A)==1: return 0
a_list = sorted(([Val,indeX] for indeX,Val in enumerate(A)), reverse=True)

rest = [indeX for val,indeX in a_list] # rest stores all the index from a_list which is sorted in decreasing order
len_rest = len(rest)
del a_list[:]
results =

for i in range(len_rest):
if i != len_rest-1:
results.append(rest[i] - min(rest[i+1:]))
else: continue

ans = max(results)
if ans < 0: return 0
else: return ans


Sample input taken for explanation:



A = [34, 8, 10, 3, 2, 80, 30, 33, 1]


Brief summary of my algorithm:



1. a_list is a list of lists which will store all the numbers from the orginal list (list A) in sorted order along with their indexes.



`a_list = [[80, 5], [34, 0], [33, 7], [30, 6], [10, 2], [8, 1], [3, 3], [2, 4], [1, 8]]`


2. rest is a list which will store all the indexes from a_list.



`rest = [5, 0, 7, 6, 2, 1, 3, 4, 8]`


(After this, a_list is deleted to empty the space)



3. Now, the crux of the logic is:
Since list is sorted in descending order, I need not take care of the constraint: A[i] <= A[j]



I will just iterate the list: rest and in each iteration, say 0th iteration, rest[0] = 5 is subtracted from the smallest remaining elements in list: rest



Each result of the iteration is stored in list: results



4. results = [5, -1, 6, 5, 1, -2, -1, -4]



5. Max of list results will give me the answer.



(It is important to note that while sorting the list we must also store the original index of the values instead of blindly sorting it.)



Now, coming to the actual problem:



On submitting my solution at interviewbit website, my code is giving correct answers to all test cases but time limit is exceeded



I am not able to figure out what how to optimise this further.



Time complexity of my code,correct me if i am wrong, is O(N log N)



Sorting takes O(N log N) time in the worst case when using sort function in python.



My main question is how to optimise this code further?



Found on www.interviewbit.com










share|improve this question















Given an array A of integers, find the maximum of j - i subjected to the constraint of A[i] <= A[j].



If there is no solution possible, return 0.



Example :



A : [3 5 4 2]



Output : 2
for the pair (3, 4)



My Code :



def maximumGap(self, A):
if len(A)==1: return 0
a_list = sorted(([Val,indeX] for indeX,Val in enumerate(A)), reverse=True)

rest = [indeX for val,indeX in a_list] # rest stores all the index from a_list which is sorted in decreasing order
len_rest = len(rest)
del a_list[:]
results =

for i in range(len_rest):
if i != len_rest-1:
results.append(rest[i] - min(rest[i+1:]))
else: continue

ans = max(results)
if ans < 0: return 0
else: return ans


Sample input taken for explanation:



A = [34, 8, 10, 3, 2, 80, 30, 33, 1]


Brief summary of my algorithm:



1. a_list is a list of lists which will store all the numbers from the orginal list (list A) in sorted order along with their indexes.



`a_list = [[80, 5], [34, 0], [33, 7], [30, 6], [10, 2], [8, 1], [3, 3], [2, 4], [1, 8]]`


2. rest is a list which will store all the indexes from a_list.



`rest = [5, 0, 7, 6, 2, 1, 3, 4, 8]`


(After this, a_list is deleted to empty the space)



3. Now, the crux of the logic is:
Since list is sorted in descending order, I need not take care of the constraint: A[i] <= A[j]



I will just iterate the list: rest and in each iteration, say 0th iteration, rest[0] = 5 is subtracted from the smallest remaining elements in list: rest



Each result of the iteration is stored in list: results



4. results = [5, -1, 6, 5, 1, -2, -1, -4]



5. Max of list results will give me the answer.



(It is important to note that while sorting the list we must also store the original index of the values instead of blindly sorting it.)



Now, coming to the actual problem:



On submitting my solution at interviewbit website, my code is giving correct answers to all test cases but time limit is exceeded



I am not able to figure out what how to optimise this further.



Time complexity of my code,correct me if i am wrong, is O(N log N)



Sorting takes O(N log N) time in the worst case when using sort function in python.



My main question is how to optimise this code further?



Found on www.interviewbit.com







python algorithm programming-challenge array time-limit-exceeded






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Dec 15 '17 at 8:55









Billal Begueradj

1




1










asked Nov 25 '16 at 12:06









kshikhar

112




112












  • Your indentation seems to be off. The method inside the class should not be on the same level as the class
    – Graipher
    Nov 25 '16 at 13:01






  • 1




    there is a solution in a o(N) complexity: see, you only have to keep track of the lowest value seen yet and compute the difference between the current point and the lowest value seen yet
    – JMat
    Nov 25 '16 at 16:19


















  • Your indentation seems to be off. The method inside the class should not be on the same level as the class
    – Graipher
    Nov 25 '16 at 13:01






  • 1




    there is a solution in a o(N) complexity: see, you only have to keep track of the lowest value seen yet and compute the difference between the current point and the lowest value seen yet
    – JMat
    Nov 25 '16 at 16:19
















Your indentation seems to be off. The method inside the class should not be on the same level as the class
– Graipher
Nov 25 '16 at 13:01




Your indentation seems to be off. The method inside the class should not be on the same level as the class
– Graipher
Nov 25 '16 at 13:01




1




1




there is a solution in a o(N) complexity: see, you only have to keep track of the lowest value seen yet and compute the difference between the current point and the lowest value seen yet
– JMat
Nov 25 '16 at 16:19




there is a solution in a o(N) complexity: see, you only have to keep track of the lowest value seen yet and compute the difference between the current point and the lowest value seen yet
– JMat
Nov 25 '16 at 16:19










1 Answer
1






active

oldest

votes

















up vote
-1
down vote













Actually in the last part, during the iteration over list named rest, its O(N^2), so, its not working.
Refer to Geeksforgeeks for O(n).






share|improve this answer

















  • 2




    Links can rot. Please include the main content in the body of your answer and provide the link for reference.
    – Dannnno
    Jul 18 at 14:02











Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














 

draft saved


draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f148088%2ffind-max-in-order-difference-in-array%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
-1
down vote













Actually in the last part, during the iteration over list named rest, its O(N^2), so, its not working.
Refer to Geeksforgeeks for O(n).






share|improve this answer

















  • 2




    Links can rot. Please include the main content in the body of your answer and provide the link for reference.
    – Dannnno
    Jul 18 at 14:02















up vote
-1
down vote













Actually in the last part, during the iteration over list named rest, its O(N^2), so, its not working.
Refer to Geeksforgeeks for O(n).






share|improve this answer

















  • 2




    Links can rot. Please include the main content in the body of your answer and provide the link for reference.
    – Dannnno
    Jul 18 at 14:02













up vote
-1
down vote










up vote
-1
down vote









Actually in the last part, during the iteration over list named rest, its O(N^2), so, its not working.
Refer to Geeksforgeeks for O(n).






share|improve this answer












Actually in the last part, during the iteration over list named rest, its O(N^2), so, its not working.
Refer to Geeksforgeeks for O(n).







share|improve this answer












share|improve this answer



share|improve this answer










answered Jul 18 at 11:35









Nipun Pruthi

1




1








  • 2




    Links can rot. Please include the main content in the body of your answer and provide the link for reference.
    – Dannnno
    Jul 18 at 14:02














  • 2




    Links can rot. Please include the main content in the body of your answer and provide the link for reference.
    – Dannnno
    Jul 18 at 14:02








2




2




Links can rot. Please include the main content in the body of your answer and provide the link for reference.
– Dannnno
Jul 18 at 14:02




Links can rot. Please include the main content in the body of your answer and provide the link for reference.
– Dannnno
Jul 18 at 14:02


















 

draft saved


draft discarded



















































 


draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f148088%2ffind-max-in-order-difference-in-array%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Terni

A new problem with tex4ht and tikz

Sun Ra