-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMaximumSubarray.php
More file actions
55 lines (46 loc) · 1.13 KB
/
MaximumSubarray.php
File metadata and controls
55 lines (46 loc) · 1.13 KB
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 MaximumSubarray
{
public static function maxSubArray(array $nums): int
{
if (empty($nums)) {
return 0;
}
[$ans, $n] = [PHP_INT_MIN, count($nums)];
for ($i = 0; $i < $n; $i++) {
$sum = 0;
for ($j = $i; $j < $n; $j++) {
$sum += $nums[$j];
$ans = max($ans, $sum);
}
}
return $ans;
}
public static function maxSubArray2(array $nums): int
{
if (empty($nums)) {
return 0;
}
[$ans, $sum] = [$nums[0], 0];
foreach ($nums as $num) {
$sum = max($sum + $num, $num);
$ans = max($ans, $sum);
}
return $ans;
}
public static function maxSubArray3(array $nums): int
{
if (empty($nums)) {
return 0;
}
$n = count($nums);
$dp = array_fill(0, $n, 0);
$dp[0] = $nums[0];
for ($i = 1; $i < $n; $i++) {
$dp[$i] = max($dp[$i - 1] + $nums[$i], $nums[$i]);
}
return max($dp);
}
}