Commonly asked Data Structures and Algorithms Problems by big tech and different solution approaches with code in Java and C

Powered by Blogger.

Wednesday, October 19, 2016

Sock Merchant







import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int c[] = new int[n];
        for(int c_i=0; c_i < n; c_i++){
            c[c_i] = in.nextInt();
        }
        Arrays.sort(c);
        int t=0;
        for (int i=0;i<n-1;i++){
            if(c[i]==c[i+1]){
                t++;
                i++;
            }
        }
        System.out.println(t);
    }
}

Explanation :

after reading data from input , we are sorting that with sort function.
then we are applying loop till array index 0 to n-1 and comparing two consecutive values and incrementing counter accordingly.

Please let me know if you are having any doubt , comment them.

0 Comments:

Post a Comment

Stats