-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathFlags.php
More file actions
66 lines (55 loc) · 1.22 KB
/
Flags.php
File metadata and controls
66 lines (55 loc) · 1.22 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
56
57
58
59
60
61
62
63
64
65
66
<?php
/**
* Flags
*
* Find the maximum number of flags that can be set on mountain peaks.
*/
include '../../Tests.class.php';
function solution($A)
{
$sizeOfA = sizeof($A);
$next = next_peaks($A);
$i = 1;
$result = 0;
while ($i * ($i - 1) <= $sizeOfA) {
$pos = 0;
$num = 0;
while ($pos < $sizeOfA && $num < $i) {
$pos = $next[$pos];
if ($pos == -1) {
break;
}
$num += 1;
$pos += $i;
}
$i++;
$result = max($result, $num);
}
return $result;
}
function peaks($A)
{
$sizeOfA = sizeof($A);
$peaks = array();
$peaks[0] = false;
for ($i = 1; $i < $sizeOfA; $i++) {
$peaks[$i] = ($A[$i - 1] < $A[$i] && $A[$i] > $A[$i + 1]) ? true : false;
}
return $peaks;
}
function next_peaks($A)
{
$sizeOfA = sizeof($A);
$peaks = peaks($A);
$next = array();
$next[$sizeOfA - 1] = -1;
for ($i = $sizeOfA - 2; $i >= 0; $i--) {
$next[$i] = $peaks[$i] ? $i : $next[$i + 1];
}
return $next;
}
$test = new Tests('Flags');
$name = 'example';
$A = array(1, 5, 3, 4, 3, 4, 1, 2, 3, 4, 6, 2);
$result = 3;
$test->run(array($A), $result, $name);