quarta-feira, 13 de julho de 2022

Codility MaxSliceSum

LocalMax > 0 this will be the interactions.



If local max never is >0 this will  be the result.




class Solution {

public int solution(int[] A) { // write your code in Java SE 8 int n=A.length; int maxSum=A[0]; int localMax=A[0]; for (int i =1;i<n;i++){ if(localMax>0) localMax=Math.max(0, localMax+A[i]); else localMax=Math.max(localMax, A[i]); maxSum= Math.max(maxSum, localMax); } return maxSum; }}

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(); } }

segunda-feira, 11 de julho de 2022

Codility various from lessons

 


Nesting

// 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 int solution(String S) { // write your code in Java SE 8 int res=0; Stack s = new Stack(); int n= S.length(); if (n%2!=0) return 0; for (char c: S.toCharArray()) { if (isOpenBracket(c)) s.push(c); else{ if (s.isEmpty()) return 0; char l = (char) s.pop(); if (!isPair(l,c)) return 0; } } if (s.isEmpty()) return 1; else return 0; } static Boolean isOpenBracket( char c){ if ( c=='(') return true; else return false; } public static Boolean isPair(char l, char r){ return l == '(' && r == ')'; } }


MaxProductOfThree

// 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 int solution(int[] A) { // write your code in Java SE 8 int n=A.length; Arrays.sort(A); int max = Math.max((A[n-1]*A[n-2]*A[n-3]), (A[0]*A[1]*A[n-1])); max = Math.max(max, (A[0]*A[1]*A[n-2])); max = Math.max(max, (A[0]*A[1]*A[n-3])); return max; } }

PassingCars

O(N) 100% solution

// 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 int solution(int[] A) {
        // write your code in Java SE 8
        final int MAXPASS=1000000000;
        int n= A.length;
        int pc=0;
        int carsPassed=0;
        int firstCar= Integer.MAX_VALUE;      

        int k=0; // number of ones - cars going west
        //count zeros
        for (int i=0; i<n; i++){
        // only count for 0 ≤ P < Q < N -> after first time a 0 appears    
        if (A[i]==1 && firstCar!= Integer.MAX_VALUE){
            k++;
        }    
       
        if(firstCar== Integer.MAX_VALUE && A[i]==0 )
            firstCar=i;
        }
        // all cars head the same way
        if (k==0 || k==n)
        return 0;

        // only count for 0 ≤ P < Q < N -> first time a 0 appears
        for (int i=firstCar; i<n; i++){
            if (A[i]==1)
            carsPassed++;

            if (A[i]==0){
                pc= pc+ (k-carsPassed);
            }

            if (pc>MAXPASS){
                return -1;
            }

        }


        return pc;
    }
}
O()

sábado, 9 de julho de 2022

PermCheck - Codility

permutation is a sequence containing each element from 1 to N once, and only once.

A set of integers will be a permutation if there are no duplicates or values bigger then the sequence. 


import java.util.Arrays;

class Solution { public int solution(int[] A) { // write your code in Java SE 8 int size= A.length; int [] holder= new int [size+1]; Arrays.fill(holder, 0); for (int t=0; t<size; t++){ if (A[t]>size) return 0; if(holder[A[t]]==0){ holder[A[t]]=A[t]; }else return 0; } return 1; } }

quarta-feira, 6 de julho de 2022

Hacker rank caesarCipher

a-> 97

z-> 122

A -> 65

Z -> 90

 public static String caesarCipher(String s, int k) {

        String res="";
        int flip=k%26;
        char [] c = s.toCharArray();   
    if (k!=26) {     
    for (int i=0;i< c.length; i++){
    if((c[i])>= 65 && (c[i])<= 90){
        
        if((c[i]+flip)<=90)
        res = res + (char) (c[i]+flip);
        else if((c[i]+flip)>90)
        res = res + (char) (c[i] -26+flip);

    }
    else if((c[i])>= 97 && (c[i])<= 122){
        
        if((c[i]+flip)<=122)
        res = res + (char) (c[i]+flip);
        else if((c[i]+flip)>122)
        res = res + (char) (c[i] -26+flip);

    }else 
        res = res + (c[i]);
 }
}
else 
 res = s;
return res;

    }

sábado, 2 de julho de 2022

Hacker Rank Time Conversion

 Taking and approach using Java java.util.Calendar, java.util.Date and java.time.format.DateTimeFormatter.


 public static String timeConversion(String s) {
    // Write your code here
    String result = "";
    SimpleDateFormat formatter = new SimpleDateFormat("hh:mm:ssa");
    try {
            Date date = formatter.parse(s);
            Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
            calendar.setTime(date);   // assigns calendar to given date 
            result= String.format("%02d:%02d:%02d", calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE),calendar.get(Calendar.SECOND));
            return result;

    } catch (ParseException e) {
            e.printStackTrace();
        }
        return result; 
    }

Hacker Rank - Binary tree (Java)

 This was my approach, it can be improved (I saw other better solution), but this works.

  1. Get parents by searching the node in tree recursivelly for each value
  2. Compare the list of parent, the first to be found is common lesser ancestor


    public static Node lca(Node root, int v1, int v2) {
        // Write your code here.
          Node result = root;
          List<Node> parentsV1 = new ArrayList<Node>();
          List<Node> parentsV2 = new ArrayList<Node>();
          setParent(root, v1, parentsV1);
          setParent(root, v2, parentsV2);   
         
         // compare parents
          for (int i =0; i<parentsV1.size(); i++){
             for (int j=0; j< parentsV2.size();j++){
                 if (parentsV2.get(j).data== parentsV1.get(i).data)
                 result = parentsV1.get(i);
         }
          }
          

          return result;

    }
    
    // returns the list of parents
    public static void setParent( Node node, int value,List<Node> parents ){
        //search node
        if (node==null){
            //enpty do nothing
            return;

        } else if (node.data==value){
            // self can be also a common ancestor
            parents.add(node);
            return;
        }else{
            parents.add(node);
            if (node.data>value){
            setParent(node.left, value,parents);}
            else{
            setParent(node.right, value, parents);    }       
        }
    }