The longest subsequence with specified difference between min and max As an input you have non-empty zero-indexed array of integers. The goal is to find the longest subsequence (any sequence obtained by removing some elements from A), where difference between min value and max value does not exceed 1.

For example, given array: 6,10,7,7,9,8 function should return 3, because 6,7,7 (or 7,7,8) is the longest qualifying subsequence.

Is this solution efficient?

    public int solution(int[] A) {
    Arrays.sort(A);
    int counter = 0;
    int res = 0;
    int val = -1;
    for (int i = 0; i &lt; A.length - 1; i++) {
        if (val == -1 &amp;&amp; A[i + 1] - A[i] &lt; 2) {
            counter = 2;
            val = A[i + 1] - A[i];
        } else if (val == 0 &amp;&amp; A[i + 1] - A[i] &lt;= 1) {
            counter++;
            val = A[i + 1] - A[i];
        } else if (val == 1 &amp;&amp; A[i + 1] - A[i] == 0) {
            counter++;
        } else {
            val = -1;
            res = Math.max(res, counter);
            counter = 0;
        }
    }
    return res;
}


Time complexity is linearithmic.
Bugs
The function doesn't handle the last series of numbers.  For example:
Input: 5 5 5       Output: 0
Input: 5 5 9 9 9   Output: 2

This can be fixed by modifying the end of the function:
    return Math.max(res, counter); // &lt;-- Accounts for last series

Also, the function fails to consider a number as the lower of two numbers once it has used it as the upper of two numbers.  For example:
Input: 5 5 6 6 6 7 7 7 10    Output: 5 (should be 6)

Here, it groups 5 and 6 together but never considers that 6 and 7 can be grouped together.