-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimple-stock-span.php
49 lines (37 loc) · 1023 Bytes
/
simple-stock-span.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
<?php
require_once 'stack.php';
function simpleStockSpan(array $quotes)
{
$spans = [];
for ($i = 0; $i < count($quotes); $i++) {
$k = 1;
$spanEnd = false;
while ($i - $k >= 0 && !$spanEnd) {
if ($quotes[$i - $k] <= $quotes[$i]) {
$k++;
} else {
$spanEnd = true;
}
}
$spans[$i] = $k;
}
return $spans;
}
function stackStockSpan(array $quotes)
{
$spans = [];
$spans[] = 1;
$stack = new Stack([0]);
for ($i = 0; $i < count($quotes); $i++) {
while (!$stack->isEmpty() && $quotes[$stack->top()] <= $quotes[$i]) {
$stack->pop();
}
$spans[$i] = $stack->isEmpty() ? $i + 1 : $i - $stack->top();
$stack->push($i);
}
return $spans;
}
// $result = simpleStockSpan([7, 11, 8, 6, 3, 8, 9]);
// var_dump($result === [1, 2, 1, 1, 1, 4, 5]);
$result = stackStockSpan([7, 11, 8, 6, 3, 8, 9]);
var_dump($result === [1, 2, 1, 1, 1, 4, 5]);