-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathStoneWall.php
More file actions
46 lines (45 loc) · 1.09 KB
/
StoneWall.php
File metadata and controls
46 lines (45 loc) · 1.09 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
<?php
echo solution([8]);
function solution($H){
/*
* 100%, https://codility.com/demo/results/training9J38JW-HSJ/
*/
//We need at least one block
$blocks=1;
$currentBlocks=array();
$currentBlocks[]=$H[0];
for($i=1; $i<count($H); $i++){
$blockFound=false;
//If the current height is higher than the previous, we need a new block + continue with the previous one
if($H[$i]>$H[$i-1]){
$blocks++;
$currentBlocks[]=$H[$i];
}
//If the current height is lower than the previous, one block ends, but we need a new block
else if($H[$i]<$H[$i-1]){
//Take the last block of the currentBlocks
while(count($currentBlocks)!=0 && $blockFound===false){
end($currentBlocks);
$key = key($currentBlocks);
if($currentBlocks[$key] === $H[$i]){
$blockFound=true;
}
else if($currentBlocks[$key] < $H[$i]){
$blockFound = true;
$currentBlocks[]=$H[$i];
$blocks++;
}
else{
unset($currentBlocks[$key]);
}
}
if(empty($currentBlocks)){
$blocks++;
$currentBlocks[]=$H[$i];
}
}
//If equal, nothing will happen
}
return $blocks;
}
?>