Codility - Voracious Fish Problem  

by ne on 2020-12-02 under Algo

There are n number of fishes in a lake, going in upstream and downstream directions. As soon as a pair meets, the big fish will eat the small one. You are given the number of fishes, there sizes and directions. Find how many will be alive at the end.

 

This is a codility problem. For complete problem details and an example : https://app.codility.com/programmers/lessons/7-stacks_and_queues/fish/

Solution:


package com.codility;

/**
 * Created by nsthethunderbolt on 15/10/17.
 */
public class SolutionFishAlive {
    class NSStack
    {
        int[] stack;
        int[] stackAge;
        int top=0;

        NSStack(int len){
            stack=new int[len];
            stackAge=new int[len];
        }
        int peek(){
            if(top!=0)
                return stack[top-1];
            else
                return -1;
        }
        int pop(){
            if(top>0)
                return stack[top--];
            else
                return -1;
        }
        void push(int elem,int age){
            stack[top]=elem;
            stackAge[top]=age;
                    top++;
        }
        int size(){
            return top;
        }

        int getAge(){
            if(top>0)
                return stackAge[top-1];
            else
                return -1;
        }
    }
    public int solution(int[] A,int[] B){
        NSStack stack=new NSStack(A.length);
        for(int i=0;i=stack.peek()){
                stack.push(B[i],A[i]);
            }else if(B[i]stack.getAge()){
                    while(A[i]>stack.getAge() && B[i]stack.getAge() && B[i]<=stack.peek())){
                        stack.push(B[i], A[i]);
                    }

                }else if(A[i]==stack.getAge()){
                    stack.push(B[i],A[i]);
                }
            }
        }
        return stack.size();
    }


    public static void main(String[] args){
        System.out.println(new SolutionFishAlive().solution(new int[]{4, 3, 2, 1, 5},new int[]{0, 1, 0, 0, 0}));        
    }
}