BestTimeToBuyAndSellStockIII   A
last analyzed

Complexity

Total Complexity 13

Size/Duplication

Total Lines 64
Duplicated Lines 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
wmc 13
eloc 37
c 2
b 0
f 0
dl 0
loc 64
rs 10

3 Methods

Rating   Name   Duplication   Size   Complexity  
A maxProfit3() 0 23 5
A maxProfit2() 0 15 3
A maxProfit() 0 20 5
1
<?php
2
3
declare(strict_types=1);
4
5
namespace leetcode;
6
7
class BestTimeToBuyAndSellStockIII
8
{
9
    public static function maxProfit(array $prices): int
10
    {
11
        [$n, $k] = [count($prices), 3];
12
        if ($n <= 0) {
13
            return 0;
14
        }
15
        $dp = array_fill(0, $n, array_fill(0, $k, [0, 0, 0]));
16
        foreach ($prices as $i => $price) {
17
            for ($j = 1; $j < $k; $j++) {
18
                if ($i - 1 < 0) {
19
                    $dp[$i][$j][0] = 0;
20
                    $dp[$i][$j][1] = -$price;
21
                } else {
22
                    $dp[$i][$j][0] = max($dp[$i - 1][$j][0], $dp[$i - 1][$j][1] + $price);
23
                    $dp[$i][$j][1] = max($dp[$i - 1][$j][1], $dp[$i - 1][$j - 1][0] - $price);
24
                }
25
            }
26
        }
27
28
        return $dp[$n - 1][$k - 1][0];
29
    }
30
31
    public static function maxProfit2(array $prices): int
32
    {
33
        $n = count($prices);
34
        if ($n <= 0) {
35
            return 0;
36
        }
37
        [$buy1, $buy2, $sell1, $sell2] = [-$prices[0], -$prices[0], 0, 0];
38
        foreach ($prices as $price) {
39
            $buy1 = max($buy1, -$price);
40
            $sell1 = max($sell1, $buy1 + $price);
41
            $buy2 = max($buy2, $sell1 - $price);
42
            $sell2 = max($sell2, $buy2 + $price);
43
        }
44
45
        return max(0, $sell1, $sell2);
46
    }
47
48
    public static function maxProfit3(array $prices): int
49
    {
50
        [$n, $ans] = [count($prices), 0];
51
        if ($n <= 0) {
52
            return 0;
53
        }
54
        [$x, $y] = [array_pad([], $n, 0), array_pad([], $n, 0)];
55
56
        for ($i = 1, $min = $prices[0]; $i < $n; $i++) {
57
            $min = min($min, $prices[$i]);
58
            $x[$i] = max($x[$i - 1], $prices[$i] - $min);
59
        }
60
61
        for ($i = $n - 2, $max = $prices[$n - 1]; $i > 0; $i--) {
62
            $max = max($max, $prices[$i]);
63
            $y[$i] = max($y[$i + 1], $max - $prices[$i]);
64
        }
65
66
        for ($i = 0; $i < $n; $i++) {
67
            $ans = max($ans, $x[$i] + $y[$i]);
68
        }
69
70
        return $ans;
71
    }
72
}
73