Professional Documents
Culture Documents
Rafal'sBlogTopCoderLongestZigZagSubsequence
an array of length of
of integers. Let
i
Z (i, 0)
Z (i, 1)
Z (i, 0) =
min
(Z (j, 1) + 1)
j<i,A[j]<A[i]
Z (i, 1) =
min
(Z (j, 0) + 1)
j<i,A[j]>A[i]
Z (0, 0) = 1
Z (0, 1) = 1
Java solution:
http://rafal.io/posts/topcoderzigzag.html
1/3
1/13/2016
Rafal'sBlogTopCoderLongestZigZagSubsequence
publicstaticintlongestZigZag(int[]A){
intn=A.length;
int[][]Z=newint[n][2];
for(inti=0;i<Z.length;i++){
Z[i]=newint[2];
}
Z[0][0]=1;
Z[0][1]=1;
intbest=1;
for(inti=1;i<n;i++){
for(intj=i1;j>=0;j){
if(A[j]<A[i])Z[i][0]=Math.max(Z[j][1]+1,Z[i][0]);
if(A[j]>A[i])Z[i][1]=Math.max(Z[j][0]+1,Z[i][1]);
}
best=Math.max(best,Math.max(Z[i][0],Z[i][1]));
}
returnbest;
}
http://rafal.io/posts/topcoderzigzag.html
2/3
1/13/2016
Rafal'sBlogTopCoderLongestZigZagSubsequence
3Comments
Rafal'sBlog
Recommend 2
Share
Login
SortbyBest
Jointhediscussion
NIL 5monthsago
Hi,Iwonderwhyshallweseparatethepositivedifferencefromnegativedifference?Don't
theysharethecommonsubproblems?
Reply Share
WeiWu>NIL 3monthsago
Forasimpleexample,considerthissequenceasinput[1,3,2,7].Thepositive
differenceshouldgiveus[1,3,2,7].Thenegativedifferenceshouldgiveus[1,3,2].
Apparentlyyouwanttoconsiderboth
Reply Share
MohammadAzeem ayearago
HiRafal,intherecursivedefinitionyouprovide,shouldn'titbemax.inplaceofmin.?
Subscribe
Reply Share
AddDisqustoyoursiteAddDisqusAdd
Privacy
(http://github.com/rafalio)
g
(http://www.goodreads.com/review/list/6752954rafal?order=d&shelf=read&sort=date_read)
(http://stackoverflow.com/users/856079/rafalszymanski)
(http://news.ycombinator.com/user?id=radicality)
http://rafal.io/posts/topcoderzigzag.html
3/3