terça-feira, 12 de julho de 2022

Codility Fish problem

After some research I did find this exercice is meant to be solved with stacks. But for me in the context of the problem it doesn't make any sense.


I solved it with a queue, a new fish arrives downstream, then we should include it in the **tail**.


In problem for some reason they want us to make it in the head, althoug they specify the fishs all swim at the same speed. More anoying is that the samples work perfectly well like this.


  

50% solution

import java.util.*;


// you can write to stdout for debugging purposes, e.g.
// System.out.println("this is a debug message");

class Solution {
     public static int solution(int[] A, int[] B) {

            // write your code in Java SE 8
            int n = A.length;
            Queue<Integer> downstream = new LinkedList<>();
            int survUpstrean = 0;
            for (int i = 0; i < n; i++) {

                if (B[i] == 1) {
                    downstream.add(A[i]);
                }
                if (B[i] == 0 && downstream.size() > 0) {
                    while (downstream.size() > 0) {
                        if (A[i] > downstream.peek()) {
                            downstream.remove();
                        } else if (A[i] < downstream.peek()) {

                            break;

                        }
                    }
                }
                if (downstream.size() == 0) {
                    survUpstrean++;
                }
            }

            return survUpstrean+downstream.size();
        }
}


    

            return survUpstrean + downstream.size();

        }



100% replacing queue with stack


// you can also use imports, for example: import java.util.*; // you can write to stdout for debugging purposes, e.g. // System.out.println("this is a debug message"); class Solution { public static int solution(int[] A, int[] B) { // write your code in Java SE 8 int n = A.length; Stack<Integer> downstream = new Stack<>(); int survUpstrean = 0; for (int i = 0; i < n; i++) { if (B[i] == 1) { downstream.push(A[i]); } if (B[i] == 0 && downstream.size()>0) { while (downstream.size() > 0) { int currFish=downstream.pop(); if (A[i] < currFish) { downstream.push(currFish); break; } } } if (downstream.size() == 0) { survUpstrean++; } } return survUpstrean + downstream.size(); } }

Sem comentários:

Enviar um comentário