Skip to content

Instantly share code, notes, and snippets.

@sadikovi
Last active August 29, 2015 14:06
Show Gist options
  • Save sadikovi/4e64e822441321a0fa5c to your computer and use it in GitHub Desktop.
Save sadikovi/4e64e822441321a0fa5c to your computer and use it in GitHub Desktop.
Codility Lesson 5
// simplier solution and neater
class Solution {
public int solution(int[] A, int[] B) {
int[] dFish = new int[A.length];
int di = -1;
int upstreamCount = 0;
for (int i=0; i<A.length; i++) {
if (B[i] == 1) {
dFish[++di] = A[i];
} else {
while (di >= 0) {
if (di < 0 || A[i] < dFish[di])
break;
di--;
}
if (di < 0)
upstreamCount++;
}
}
return (di+1) + upstreamCount;
}
}
// longer solution and perhaps more complicated
class Solution {
int[] fish;
private int index = -1;
public int solution(int[] A, int[] B) {
fish = new int[A.length];
int alivefish = 0;
boolean isFirstDownstream = false;
for (int i=0; i<A.length; i++) {
if (B[i] == 0) {
if (!isFirstDownstream) {
alivefish += 1;
} else {
if (size(fish) == 0) {
alivefish += 1;
} else {
while(size(fish) > 0 && A[peek(fish)] < A[i])
pop(fish);
if (size(fish) == 0) alivefish += 1;
}
}
} else {
isFirstDownstream = true;
push(fish, i);
}
}
alivefish += size(fish);
return alivefish;
}
private void push(int[] a, int i) {
index++;
a[index] = i;
}
private void pop(int[] a) {
if (index >= 0) index--;
}
private int peek(int[] a) {
if (index < 0 || index > (a.length-1)) return -1;
return a[index];
}
private int size(int[] a) {
return (index >= 0)?index+1:0;
}
}
// StoneWall (Manhattan Skyline problem)
class Solution {
public int solution(int[] H) {
int blocks = 0;
int[] stack = new int[H.length];
int index = -1;
for (int i=0; i<H.length; i++) {
while (index >= 0 && stack[index] > H[i])
index--;
if (index == -1 || stack[index] != H[i]) {
blocks++;
stack[++index] = H[i];
}
}
return blocks;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment