Created
July 8, 2016 14:39
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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