Java TreeMap Solution
Intuition\nFor every number, we want to pair the smallest number that is just greater than that number. If there isn\'t a greater number, then we want to pair i
# Intuition\nFor every number, we want to pair the smallest number that is just greater than that number. If there isn\'t a greater number, then we want to pair it with the smallest unpaired number.\n\nYou can use an ordered set to find the next higher number in logarithmic time.\n\n# Approach\nAdd all the elements to a sorted map. Iterate through all the elements looking for the next number that is greater than the current number. For each number we pair, we need to remove it from the sorted map by decrementing the count by 1. If the count reaches 0, then remove it from the set\n\n# Complexity\n- Time complexity:\nO(nlogn)\n\n- Space complexity:\nO(n)\n# Code\n```\nclass Solution {\n    public int maximizeGreatness(int[] nums) {\n\n        TreeMap<Integer, Integer> map = new TreeMap<>();\n\n        for (var n : nums) map.merge(n, 1, Integer::sum);\n\n        int ans = 0;\n        for (var num : nums) {\n            var key = map.higherKey(num);\n            if (key != null) {\n                //we found a higher element to pair with num\n                ans++;\n            } else {\n                //we didn\'t find a higher element, so choose the smallest available number to pair\n                key = map.firstKey();\n            }\n\n            //decrement the counter. If the counter would reach 0, then remove it.\n            map.merge(key, -1, Integer::sum);\n\n            if (map.get(key) == 0) {\n                map.remove(key);\n            }\n        }\n        return ans;\n    }\n}\n```
['Ordered Map', 'Java']