
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 i1 .
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 ith 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 leftend. 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. 