Show problems as
Classic problem #896EasyArray

Monotonic Array

Real-world version: One-Way Altitude Log
Tracked in this browser only
Read Monotonic Array on LeetCode(opens in a new tab)

The statement here is our own: the same inputs, outputs and technique.

A survey drone logs its altitude relative to sea level once a second, giving the array nums. Altitudes may be negative when the drone flies below sea level.

The flight is called one-way when the drone never reverses its vertical direction: either every reading is greater than or equal to the reading before it, or every reading is less than or equal to the reading before it. Holding altitude is not a reversal, so a run of equal readings is fine either way, and a log with a single reading is one-way.

Return true when the log is one-way and false otherwise.

Examples

Example 1

Input
nums = [3, 3, 5, 9, 9]
Output
true

Each reading is at least as high as the one before it, so the drone never descends.

Example 2

Input
nums = [1, 2, 2, 1]
Output
false

The drone climbs from 1 to 2 and later descends from 2 to 1, so the log holds both a rise and a fall.

Example 3

Input
nums = [2, 2, 1]
Output
true

The drone holds 2 and then descends, and holding is not a reversal, so every reading is at most the reading before it.

Constraints

  • 1 <= nums.length <= 10^5
  • -10^5 <= nums[i] <= 10^5

The signature

The editor starts with this. It matches the parent problem's shape, so a solution that works here works on a standard judge unchanged.

Python
def is_monotonic(nums: list[int]) -> bool:
Java
public boolean isMonotonic(int[] nums)