Trying to solve this challenge on codility fish challenge I cannot understand why not all the tests are passed by my code.
function solution($A, $B) {
// write your code in PHP7.0
$stack =[];
foreach($A as $key =>$value) {
if(empty($stack)){
array_push($stack,$key);
}
else if($B[count($stack)-1] == 1 && $B[$key]==0 )
{
if($value > $A[count($stack)-1])
{
array_pop($stack);
array_push($stack,$key);
}
}
else array_push($stack,$key);
}
return count($stack);
}
Swift solution 100%:
public func solution(_ A : inout [Int], _ B : inout [Int]) -> Int {
var stack = [(size: Int, direction: Int)]()
outer:
for i in 0..<A.count {
let currentFish = (size: A[i], direction: B[i])
guard !stack.isEmpty, currentFish.direction == 0, stack.last?.direction == 1 else {
stack.append(currentFish)
continue
}
while stack.last?.direction == 1 {
if stack.last!.size > currentFish.size {
continue outer
} else {
stack.popLast()
}
}
stack.append(currentFish)
}
return stack.count
}