1 | <?php |
||
2 | |||
3 | declare(strict_types=1); |
||
4 | |||
5 | namespace leetcode; |
||
6 | |||
7 | class BestTimeToBuyAndSellStockII |
||
8 | { |
||
9 | public static function maxProfit(array $prices): int |
||
10 | { |
||
11 | $n = count($prices); |
||
12 | if ($n <= 0) { |
||
13 | return 0; |
||
14 | } |
||
15 | $dp = array_fill(0, $n, array_fill(0, $n, [0, 0])); |
||
16 | foreach ($prices as $i => $price) { |
||
17 | if ($i - 1 < 0) { |
||
18 | $dp[0][0] = 0; |
||
19 | $dp[0][1] = -$price; |
||
20 | } else { |
||
21 | $dp[$i][0] = max($dp[$i - 1][0], $dp[$i - 1][1] + $price); |
||
22 | $dp[$i][1] = max($dp[$i - 1][1], $dp[$i - 1][0] - $price); |
||
23 | } |
||
24 | } |
||
25 | |||
26 | return $dp[$n - 1][0]; |
||
27 | } |
||
28 | |||
29 | public static function maxProfit2(array $prices): int |
||
30 | { |
||
31 | if (count($prices) <= 0) { |
||
32 | return 0; |
||
33 | } |
||
34 | [$maxProfit, $minPrice] = [0, -$prices[0]]; |
||
35 | foreach ($prices as $price) { |
||
36 | $maxProfit = max($maxProfit, $minPrice + $price); |
||
37 | $minPrice = max($minPrice, $maxProfit - $price); |
||
38 | } |
||
39 | |||
40 | return $maxProfit; |
||
41 | } |
||
42 | |||
43 | public static function maxProfit3(array $prices): int |
||
44 | { |
||
45 | $n = count($prices); |
||
46 | if ($n <= 0) { |
||
47 | return 0; |
||
48 | } |
||
49 | $ans = []; |
||
50 | for ($i = $n - 2; $i >= 0; $i--) { |
||
51 | $ans[] = max($prices[$i + 1] - $prices[$i], 0); |
||
52 | } |
||
53 | |||
54 | return array_sum($ans); |
||
0 ignored issues
–
show
Bug
Best Practice
introduced
by
![]() |
|||
55 | } |
||
56 | |||
57 | public static function maxProfit4(array $prices): int |
||
58 | { |
||
59 | $n = count($prices); |
||
60 | if ($n <= 0) { |
||
61 | return 0; |
||
62 | } |
||
63 | $ans = 0; |
||
64 | for ($i = 1; $i < $n; $i++) { |
||
65 | $ans += max(0, $prices[$i] - $prices[$i - 1]); |
||
66 | } |
||
67 | |||
68 | return $ans; |
||
69 | } |
||
70 | } |
||
71 |