MonotonicArray   A
last analyzed

Complexity

Total Complexity 11

Size/Duplication

Total Lines 35
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 11
eloc 19
c 2
b 0
f 0
dl 0
loc 35
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
A isMonotonic() 0 12 4
B isMonotonic2() 0 19 7
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class MonotonicArray
8
{
9
    public static function isMonotonic(array $arr): bool
10
    {
11
        if (empty($arr)) {
12
            return false;
13
        }
14
        $inc = $dec = true;
15
        for ($i = 1, $n = count($arr); $i < $n; $i++) {
16
            $inc &= $arr[$i - 1] <= $arr[$i];
17
            $dec &= $arr[$i - 1] >= $arr[$i];
18
        }
19
20
        return $inc || $dec;
21
    }
22
23
    public static function isMonotonic2(array $arr): bool
24
    {
25
        if (empty($arr)) {
26
            return false;
27
        }
28
        $inc = $dec = true;
29
        for ($i = 0, $n = count($arr) - 1; $i < $n; $i++) {
30
            if ($arr[$i] > $arr[$i + 1]) {
31
                $inc = false;
32
            }
33
            if ($arr[$i] < $arr[$i + 1]) {
34
                $dec = false;
35
            }
36
            if ($inc === false && $dec === false) {
37
                return false;
38
            }
39
        }
40
41
        return true;
42
    }
43
}
44