-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathDietPlanPerformance.php
55 lines (49 loc) · 1.32 KB
/
DietPlanPerformance.php
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
44
45
46
47
48
49
50
51
52
53
54
55
<?php
declare(strict_types=1);
namespace leetcode;
class DietPlanPerformance
{
public static function dietPlanPerformance(array $calories, int $k, int $lower, int $upper): int
{
if (empty($calories) || $k <= 0) {
return 0;
}
$res = $sum = 0;
for ($i = 0; $i < $k - 1; $i++) {
$sum += $calories[$i];
}
for ($i = $k - 1, $n = count($calories); $i < $n; $i++) {
$sum += $calories[$i];
if ($sum < $lower) {
$res--;
}
if ($sum > $upper) {
$res++;
}
$sum -= $calories[$i - $k + 1];
}
return $res;
}
public static function dietPlanPerformance2(array $calories, int $k, int $lower, int $upper): int
{
if (empty($calories) || $k <= 0) {
return 0;
}
[$res, $sum, $n] = [0, 0, count($calories)];
for ($i = 0; $i < $n; $i++) {
$sum += $calories[$i];
if ($i >= $k) {
$sum -= $calories[$i - $k];
}
if ($i >= $k - 1) {
if ($sum < $lower) {
$res--;
}
if ($sum > $upper) {
$res++;
}
}
}
return $res;
}
}