Monotonic Array
Real-world version: One-Way Altitude LogThe 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.
def is_monotonic(nums: list[int]) -> bool:public boolean isMonotonic(int[] nums)Checking your plan…
How this problem was checked
- Passed: Reference solution run against 13 test cases: 13 passed
- Passed: 3 worked examples confirmed by running the code
- Passed: 0 eight-word sequences shared with the parent problem's text
- Passed: Agrees with an independent brute-force solution on random inputs
- Passed: Test set shown to catch deliberately broken solutions
- Passed: Reviewed by a separate quality pass
- Passed: Function arity matches the parent problem's