Lonely M's array

The lonely M is again playing with his array a1,a2,...,an (as playing with his array is the only choice), he wants to choose a subsequence of array like b1,b2,...,bm that b1≥b2≤b3≥b4...≤(≥if m≡0 (mod 2))bm.

What is the maximum length of subsequence that M can choose which satisfies above condition?

Subsequence of an array can be obtained by erasing some (possibly zero) elements from the array. You can erase any elements, not necessarily going successively. The remaining elements preserve their order.

Example:

Input: n=10, arr[]={ 5, 7, 11, 13, 19, 17, 8, 4, 10, 19 }
Output: 3

Approach

Java

public class LonelyArray {
    public static void main(String args[]) {
        int i, ans, init;
        boolean ge;
        int n = 10;
        int[] a = { 5, 7, 11, 13, 19, 17, 8, 4, 10, 19 };
        if (n == 1) {
            System.out.println("1");
            return;
        }
        init = n - 1;
        for (i = 0; i < n - 1; i++) {
            if (a[i] >= a[i + 1]) {
                init = i;
                break;
            }
        }
        ans = 1;
        ge = false;
        for (i = init + 1; i < n - 1; i++) {
            if (!ge && a[i] <= a[i + 1]) {
                ans++;
                ge = !ge;
            } else if (ge && a[i] >= a[i + 1]) {
                ans++;
                ge = !ge;
            }
        }
        ans++;
        System.out.println(ans);
    }

}


No comments:

Post a Comment