0
$\begingroup$

I have to create an algorithm for homework, but cant figure out where to start.

The divide and conquer algorithm muse be O(nlgn) and returns a pair of numbers p and q in an array A. p must appear before q in the array, and q-p must be the highest possible value

heres and example I made up:

A=[1,4,12,5,9,1,3,8]

the return values would be p=1 & q=12

avi
1,4834 gold badges24 silver badges39 bronze badges
asked Sep 28, 2013 at 23:21
$\endgroup$
3
  • $\begingroup$ I must be an idiot. Kept on thinking and wondering what is q-p. If anyone is still looking then it's difference of q,p. Simply put, OP is looking for pair numbers in the array which has highest difference. Here 12-1 giving 11. Next highest difference would be 12-3 = 9. $\endgroup$ Commented Sep 29, 2013 at 12:35
  • 1
    $\begingroup$ @avi There's also the restriction that $p$ must appear before $q$ in the array so the next-highest acceptable difference is not 12ドル-3=9$ but 12ドル-4=9-1=8$. $\endgroup$ Commented Sep 29, 2013 at 15:34
  • $\begingroup$ oh, you are right. I did mistake again. $\endgroup$ Commented Sep 29, 2013 at 15:39

1 Answer 1

5
$\begingroup$

Hint: Divide $A$ evenly into two smaller arrays $A_1,A_2,ドル and solve the problem (recursively) on $A_1$ and $A_2$. Can that help you find the optimum on $A$? Don't forget you're allowed to use extra processing costing up to $O(n)$.

Another hint: Suppose that $p,q$ is the optimal pair for $A$. Either $p,q \in A_1,ドル or $p,q \in A_2,ドル or neither of these cases is true. What can you say in the third case about $p$ and $q$?


As an aside, this can be solved in $O(n),ドル in fact even online. We maintain the minimal element seen so far $m,ドル and the maximum difference $D = q-p$ over elements seen so far. Upon getting a new element $x,ドル we put $D = \max(D,x-m)$ and $m = \min(x,m),ドル and update $p,q$ with $m,x$ if needed.

answered Sep 29, 2013 at 2:00
$\endgroup$
1
  • $\begingroup$ thanks :) (and good catch there), i had not read the question carefully, and thus leading to a trivial mistake.. i removed the answer (no point in having a wrong answer).. thanks again :) $\endgroup$ Commented Sep 29, 2013 at 7:34

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.