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

Sem comentários:

Enviar um comentário