DietPlanPerformance   A
last analyzed

Complexity

Total Complexity 15

Size/Duplication

Total Lines 47
Duplicated Lines 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 15
eloc 27
c 1
b 0
f 0
dl 0
loc 47
rs 10

2 Methods

Rating   Name   Duplication   Size   Complexity  
B dietPlanPerformance() 0 21 7
B dietPlanPerformance2() 0 22 8
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class DietPlanPerformance
8
{
9
    public static function dietPlanPerformance(array $calories, int $k, int $lower, int $upper): int
10
    {
11
        if (empty($calories) || $k <= 0) {
12
            return 0;
13
        }
14
        $res = $sum = 0;
15
        for ($i = 0; $i < $k - 1; $i++) {
16
            $sum += $calories[$i];
17
        }
18
        for ($i = $k - 1, $n = count($calories); $i < $n; $i++) {
19
            $sum += $calories[$i];
20
            if ($sum < $lower) {
21
                $res--;
22
            }
23
            if ($sum > $upper) {
24
                $res++;
25
            }
26
            $sum -= $calories[$i - $k + 1];
27
        }
28
29
        return $res;
30
    }
31
32
    public static function dietPlanPerformance2(array $calories, int $k, int $lower, int $upper): int
33
    {
34
        if (empty($calories) || $k <= 0) {
35
            return 0;
36
        }
37
        [$res, $sum, $n] = [0, 0, count($calories)];
38
        for ($i = 0; $i < $n; $i++) {
39
            $sum += $calories[$i];
40
            if ($i >= $k) {
41
                $sum -= $calories[$i - $k];
42
            }
43
            if ($i >= $k - 1) {
44
                if ($sum < $lower) {
45
                    $res--;
46
                }
47
                if ($sum > $upper) {
48
                    $res++;
49
                }
50
            }
51
        }
52
53
        return $res;
54
    }
55
}
56