-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMonotonicArray.php
More file actions
43 lines (37 loc) · 951 Bytes
/
MonotonicArray.php
File metadata and controls
43 lines (37 loc) · 951 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
<?php
declare(strict_types=1);
namespace leetcode;
class MonotonicArray
{
public static function isMonotonic(array $arr): bool
{
if (empty($arr)) {
return false;
}
$inc = $dec = true;
for ($i = 1, $n = count($arr); $i < $n; $i++) {
$inc &= $arr[$i - 1] <= $arr[$i];
$dec &= $arr[$i - 1] >= $arr[$i];
}
return $inc || $dec;
}
public static function isMonotonic2(array $arr): bool
{
if (empty($arr)) {
return false;
}
$inc = $dec = true;
for ($i = 0, $n = count($arr) - 1; $i < $n; $i++) {
if ($arr[$i] > $arr[$i + 1]) {
$inc = false;
}
if ($arr[$i] < $arr[$i + 1]) {
$dec = false;
}
if ($inc === false && $dec === false) {
return false;
}
}
return true;
}
}