Skip to content

Commit

Permalink
Fish
Browse files Browse the repository at this point in the history
  • Loading branch information
zengfenfei committed Apr 28, 2016
1 parent 209a465 commit d2b5edd
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
25 changes: 25 additions & 0 deletions Fish.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package codility

// https://codility.com/programmers/task/fish/
func Fish(A []int, B []int) int {
n := len(A)
count := n
downStack := make([]int, 0)
for i := 0; i < n; i++ {
if B[i] == 1 {
downStack = append(downStack, A[i]) // stack push
} else {
j := len(downStack) - 1
// eats downstream fish, downstack pop
for ; j >= 0 && downStack[j] < A[i]; j-- {
count--
}
// if downstream fish is not eaten up, then the current upstream fish must be eaten
if j >= 0 {
count--
}
downStack = downStack[:j+1]
}
}
return count
}
17 changes: 17 additions & 0 deletions example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,23 @@ import (
"testing"
)

func ExampleFish() {
A, B := make([]int, 5), make([]int, 5)
A[0] = 4
A[1] = 3
A[2] = 2
A[3] = 1
A[4] = 5

B[0] = 0
B[1] = 1
B[2] = 0
B[3] = 0
B[4] = 0
fmt.Println(Fish(A, B))
// Output: 2
}

func ExampleNumberOfDiscIntersections() {
A := make([]int, 6)
A[0] = 1
Expand Down

0 comments on commit d2b5edd

Please sign in to comment.