You are on page 1of 3

1/13/2016

Rafal'sBlogTopCoderLongestZigZagSubsequence

TopCoder Longest ZigZag


Subsequence
Posted on November 28, 2013
Last updated on November 28, 2013

Solution to TopCoder ZigZag (http://community.topcoder.com/stat?


c=problem_statement&pm=1259&rd=4493).
Let

an array of length of

subsequence ending at index

of integers. Let
i

Z (i, 0)

with a positive difference (the second last element of

it is strictly less than the last element), and let


subsequence ending at index

be the longest zig-zag

Z (i, 1)

be the longest zig-zag

with a negative difference. Then:

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;
}

Longest zigzag subsequence


Markdown SHA1: 78cdfd42f02c0b91a65776233fddbc05cd98faed

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

You might also like