Skip to content

Instantly share code, notes, and snippets.

@tiagopereira17
Created July 8, 2016 14:39
Show Gist options
  • Save tiagopereira17/f3d6d8e626f1a8d0bde1c72aa5659b38 to your computer and use it in GitHub Desktop.
Save tiagopereira17/f3d6d8e626f1a8d0bde1c72aa5659b38 to your computer and use it in GitHub Desktop.
N voracious fish are moving along a river. Calculate how many fish are alive.
import java.util.Stack;
public class Fish {
public int solution(int[] A, int[] B) {
if(A == null || B == null || A.length != B.length) {
return -1;
}
Stack<Integer> downstream = new Stack<>();
int alive = 0;
for(int i = 0; i < A.length; i++) {
if(B[i] == 0) {
while(!downstream.isEmpty()) {
if(downstream.peek() < A[i]) {
downstream.pop();
} else {
break;
}
}
if(downstream.isEmpty()) {
alive++;
}
} else {
downstream.push(A[i]);
}
}
alive += downstream.size();
return alive;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment