JOIN
Get Time
forums   
Search | Watch Thread  |  My Post History  |  My Watches  |  User Settings
View: Flat (newest first)  | Threaded  | Tree
Previous Thread  |  Next Thread
How to find maximum element on left hand side of an element which is smaller than the element in an array? | Reply
Suppose I have an array of integers like this:

{ 3, 1, 6, 8, 2, 0, 1 }

I need to find the maximum element on the left hand side of each element which is smaller than the element, or print -1 if that maximum element doesn't exist. So, solution for this problem will be:

{ -1, -1, 3, 6, 1, -1, 0 }

I can solve this in O(n^2) using two loops. Inner loop will find maximum element which is smaller than the given element. But is there any better approach to solve this?
Re: How to find maximum element on left hand side of an element which is smaller than the element in an array? (response to post by d@rk_sh@dow) | Reply
Hi,

you can keep( or save) index value (k) of the number found a[k] which is less than a[i] ( where k < i ) and also the max of each element from 0 to i-1 .

Then, when you check the same thing for i+1 th element, you gradually come to left. When you will come to a[i], you will see that this element has already found its desired value whose index is stored in the i-th element of an array. You can then compare this value with the new one and can take decision.

This algorithm has worst case complexity of O(n2), when all the values will be -1. Otherwise, this algorithm is much faster than O(n2). I solved this problem in a contest and got accepted.

If I could not properly explain, please see the illustration below:

index ={ -1, -1, -1, -1, -1, -1, -1}
input = { 3, 1, 6, 8, 2, 0, 1 }

start with value=3, index=0
there is no value left in three, so index[0] = -1 will remain unchanged.

value=1, index=1
loop through left. Found index[0]=-1 , so will have to go more left, but cannot go beyond 0.
So, index[1] = -1

value=6, index=2
loop through left. Found index[1]=-1 , so will have to go more left
Found index[0] = 3. 3 is less than 6 and also the max value till left-end.
So, we have to keep the index value of 3 as our memory.
So, index[2] = 0

value=8, index=3 (the tricky part is here!)
loop through left. Found index[2]=0 . What does this mean?
This says us, hey! I am index number 2 and I have found my best answer value which is stored in index number 0.
Getting this information, you found that index number 0 contains 3 which is the best value for 6.
Now, we just have to keep the index value of max(3,6)
So, index[3] = 2

This is how the process will go on and fill up the index array.
Finally, to print the output, you just check index array, if there is a -1, you just print -1.
If index[i] contains any other value than -1,
you just print -> input[ index[i] ] like this.

Hope I could make it understood.
Please let me know if you find any problem in the solution.
RSS