Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.BufferedReader;
- import java.io.InputStreamReader;
- import java.util.Arrays;
- import static java.lang.Integer.parseInt;
- /**
- * Created by bugkiller on 21/10/18.
- */
- class LongestZigZagSubsequence {
- public static void main(String[] args) throws Exception {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- int t = parseInt(br.readLine());
- while (t-- > 0) {
- int n = parseInt(br.readLine());
- String s[] = br.readLine().split("\\s");
- int a[] = new int[n];
- for (int i = 0; i < n; i++) {
- a[i] = parseInt(s[i]);
- }
- System.out.println(longestZigZagSubsequence(a));
- }
- }
- //This is the incorrect solution and needs to be fixed.
- public static int longestZigZagSubsequence(int a[]) {
- int ans = 0;
- for (int i = 0; i < a.length; i++) {
- ans = max(ans,
- longestZigZagSubsequence(a, i, Integer.MIN_VALUE, true),
- longestZigZagSubsequence(a, i, Integer.MAX_VALUE, false));
- }
- return ans;
- }
- private static int longestZigZagSubsequence(int[] a, int idx, int prev, boolean biggerElementNeeded) {
- if (a.length == idx) return 0;
- if (a[idx] > prev && biggerElementNeeded) {
- return 1 + longestZigZagSubsequence(a, idx + 1, a[idx], false);
- }
- if (!biggerElementNeeded && prev > a[idx]) {
- return 1 + longestZigZagSubsequence(a, idx + 1, a[idx], true);
- }
- return longestZigZagSubsequence(a, idx + 1, prev, biggerElementNeeded);
- }
- private static int max(int a, int b, int c) {
- return Integer.max(a, Integer.max(b, c));
- }
- }
Add Comment
Please, Sign In to add comment