Created
October 1, 2014 23:49
-
-
Save jimexist/103c8151e6da730506b2 to your computer and use it in GitHub Desktop.
Another solution for ZigZag
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| public class ZigZag { | |
| public static int longestZigZag(int[] sequence) { | |
| final int n = sequence.length; | |
| int[] positive = new int[n]; | |
| int[] negative = new int[n]; | |
| for (int i=0; i<n; ++i) { | |
| positive[i] = negative[i] = 1; | |
| } | |
| for (int i=1; i<n; ++i) { | |
| for (int j=0; j<i; ++j) { | |
| if (sequence[i] > sequence[j]) { | |
| negative[i] = Math.max(negative[i], positive[j] + 1); | |
| } else if (sequence[i] < sequence[j]) { | |
| positive[i] = Math.max(positive[i], negative[j] + 1); | |
| } | |
| } | |
| } | |
| return Math.max(positive[n-1], negative[n-1]); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment