Skip to content
On this page

896. Monotonic Array

https://leetcode.com/problems/monotonic-array/

js
/**
 * @param {number[]} A
 * @return {boolean}
 */
var isMonotonic = function(A) {
  let temp = A[0]
  let asc = undefined

  for (let i of A) {
    if (i === temp) {
      continue
    } else if (asc === undefined) {
      asc = i > temp
    } else {
      if ((i > temp) !== asc) {
        return false
      }
    }
    temp = i
  }

  return true
}
py
class Solution:

    def isMonotonic(self, A):
        """
        :type A: List[int]
        :rtype: bool
        """
        temp = A[0]
        asc = None
        for i in A:
            if i == temp:
                continue
            elif asc is None:
                asc = i > temp
            else:
                if (i > temp) != asc:
                    return False
            temp = i

        return True