An array is_monotonic_if it is either monotone increasing or monotone decreasing.

class Solution {
    public boolean isMonotonic(int[] A) {
        if(A == null || A.length <= 1)
            return true;

        int i = 0;
        for(; i < A.length - 1; i++) {
            if(A[i] < A[i + 1])
                break;
        }

        if(i == A.length - 1)
            return true;

        i = 0;
        for(; i < A.length - 1; i++) {
            if(A[i] > A[i + 1])
                break;
        }

        return i == A.length - 1;
    }
}

results matching ""

    No results matching ""