-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathHouseRobberII.php
62 lines (54 loc) · 1.5 KB
/
HouseRobberII.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
56
57
58
59
60
61
62
<?php
declare(strict_types=1);
namespace leetcode;
class HouseRobberII
{
public static function rob(array $nums): int
{
$n = count($nums);
if ($n === 0) {
return 0;
}
if ($n === 1) {
return $nums[0];
}
if ($n === 2) {
return max($nums[0], $nums[1]);
}
$prev = self::helper($nums, 0, $n - 2);
$next = self::helper($nums, 1, $n - 1);
return max($prev, $next);
}
public static function rob2(array $nums): int
{
$n = count($nums);
if ($n === 0) {
return 0;
}
if ($n === 1) {
return $nums[0];
}
if ($n === 2) {
return max($nums[0], $nums[1]);
}
$prev = $next = array_fill(0, $n + 1, 0);
[$prev[0], $prev[1], $next[0], $next[1]] = [0, $nums[0], 0, 0];
for ($i = 2; $i <= $n; $i++) {
$prev[$i] = max($prev[$i - 1], $prev[$i - 2] + $nums[$i - 1]);
$next[$i] = max($next[$i - 1], $next[$i - 2] + $nums[$i - 1]);
}
return max($prev[$n - 1], $next[$n]);
}
private static function helper(array $nums, int $start, int $end): int
{
$prev = $nums[$start];
$next = max($prev, $nums[$start + 1]);
$result = $next;
for ($i = $start + 2; $i <= $end; $i++) {
$result = max($prev + $nums[$i], $next);
$prev = $next;
$next = $result;
}
return $result;
}
}