Sales by Match

  • + 0 comments

    JAVA

    we just need to go through the n elements once (if we focus on performance and maybe not so clean code). I ve used the boolean array for memory optimization too, which makes the code a bit less readable too, possibly:

    public static int sockMerchant(int n, List<Integer> ar) {
             boolean[] socks = new boolean[101];
             int sockPairs = 0;
             
             for (int x: ar) {
                if (!socks[x]) {
                    socks[x] ^= true;
                } else {
                    socks[x] ^= true;
                    sockPairs++;
                }
             }
             
             return sockPairs;
        }