Created
April 5, 2014 03:30
-
-
Save jimexist/9987133 to your computer and use it in GitHub Desktop.
given an array of integer, returns the maximun length of zig-zag subsequence
This file contains 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 final class Zigzag { | |
private Zigzag() {} | |
/** | |
* given an array of integer, returns the maximun length of zig-zag | |
* subsequence | |
*/ | |
public static int zigzagSequence(int[] arr) { | |
if (arr.length < 2) { | |
return arr.length; | |
} | |
int[] max = new int[arr.length]; | |
boolean[] direction = new boolean[arr.length]; | |
max[0] = 1; | |
max[1] = arr[1] == arr[0] ? 1 : 2; | |
direction[1] = arr[0] < arr[1]; | |
for (int i=2; i<arr.length; ++i) { | |
max[i] = 1; | |
for (int j=0; j<i; ++j) { | |
if (max[j] + 1 > max[i]) { | |
if (arr[j] < arr[i] && direction[j] == false) { | |
max[i] = max[j] + 1; | |
direction[i] = true; | |
} else if (arr[j] > arr[i] && direction[j] == true) { | |
max[i] = max[j] + 1; | |
direction[i] = false; | |
} else if (arr[j] != arr[i] && max[i] == 1) { | |
max[i] = 2; | |
direction[i] = arr[i] > arr[j]; | |
} | |
} | |
} | |
} | |
return max[max.length-1]; | |
} | |
public static void main(String[] args) { | |
int[] data = new int[args.length]; | |
for (int i=0; i<args.length; ++i) { | |
data[i] = Integer.parseInt(args[i]); | |
} | |
System.out.println(zigzagSequence(data)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment