Maximum Elegance | Easy to Understand | Faster than 100%
\n\n# Code\n\nclass Solution {\n    public long findMaximumElegance(int[][] items, int k) {\n        PriorityQueue<int[]>pq=new PriorityQueue<>((a,b)->a[0]-b[0]
\n\n# Code\n```\nclass Solution {\n    public long findMaximumElegance(int[][] items, int k) {\n        PriorityQueue<int[]>pq=new PriorityQueue<>((a,b)->a[0]-b[0]);\n        HashSet<Integer> hs=new HashSet<>();\n        List<int[]>comp=new ArrayList<>();\n\n        Arrays.sort(items,(a,b)->b[0]-a[0]);\n\n        int n=items.length;\n        long sum=0;\n\n        for(int i=0;i<n && hs.size()<=k;i++){\n            int profit=items[i][0];\n            int cat=items[i][1];\n\n            if(!hs.contains(cat) && hs.size()<k){\n                hs.add(cat);\n                sum+=profit;\n                pq.add(items[i]);\n            }else{\n                comp.add(items[i]);\n            }\n        }\n\n        HashSet<Integer> dup=new HashSet<>();\n\n        for(int []a:comp){\n\n            if(pq.size()<k){\n                pq.add(a);\n                dup.add(a[1]);\n                sum+=a[0];\n                continue;\n            }\n\n            int[] potrem=pq.peek(); //potential element to be removed\n\n            //If the new element has the same category \n            //as the potential element or\n            //if there are 1 or more elements having same category\n            //as potential element break because it is irrelevant to \n            //check for others\n            if(potrem[1]==a[1] || dup.contains(potrem[1])){\n                break;\n            }else{\n                int len=hs.size();\n\n                //Check if its actually beneficial to loose a\n                //category and gain another profit of the same category\n                if((sum+a[0]-potrem[0])+(len-1)*(len-1)>sum+(len*len)){\n                    sum+=a[0]-potrem[0];\n                    hs.remove(potrem[1]);\n                    pq.remove();\n                    pq.add(a);\n                    dup.add(a[1]);\n                }\n                \n            }\n        }\n        return sum+1L*(hs.size())*(hs.size());\n    }\n}\n```
['Java']