💥💥 Beats 100% on runtime and memory [EXPLAINED]
IntuitionI first need to group the elements in the array based on their values and their frequencies. By sorting the array, I can easily handle consecutive iden
# Intuition
I first need to group the elements in the array based on their values and their frequencies. By sorting the array, I can easily handle consecutive identical numbers. The goal is to find the maximum number of elements I can select while respecting certain conditions on consecutive values.

# Approach
I sorted the array, then used a list of pairs to track the frequency of each unique number. For each group of numbers, I check if the next group is a consecutive value or a non-consecutive one, and adjust the answer accordingly.

# Complexity
- Time complexity:
Sorting the array takes O(n log n), and iterating through the list to process the frequencies takes O(n). So, the overall time complexity is O(n log n).

- Space complexity:
I used a list of pairs to store the frequencies, which takes O(n) space. So, the space complexity is O(n).

# Code
```kotlin []
class Solution {
    fun maxSelectedElements(nums: IntArray): Int {
        nums.sort()
        val v = mutableListOf<Pair<Int, Int>>()
        var value = nums[0] 
        var count = 0
        for (x in nums) {
            if (x == value) {
                count++
            } else {
                v.add(Pair(value, count))
                value = x
                count = 1
            }
        }
        v.add(Pair(value, count))
        val n = v.size
        var ans = 1
        var change = v[0].first
        var j = v[0].first
        for (i in 0 until n) {
            if (i == n - 1) {
                val y = v[i].second > 1
                ans = maxOf(ans, v[i].first - j + 1 + if (y) 1 else 0)
                break
            }
            if (v[i].first + 1 == v[i + 1].first) {
                if (v[i].second > 1) {
                    v[i + 1] = Pair(v[i + 1].first, v[i + 1].second + 1)
                }
            } else if (v[i].first + 2 == v[i + 1].first) {
                if (v[i].second > 1) {
                    change = v[i + 1].first
                } else {
                    ans = maxOf(ans, v[i].first - j + 1)
                    j = change + 1
                    change = v[i + 1].first
                }
            } else {
                val y = v[i].second > 1
                ans = maxOf(ans, v[i].first - j + 1 + if (y) 1 else 0)
                change = v[i + 1].first
                j = v[i + 1].first
            }
        }
        return ans
    }
}

```
['Array', 'Hash Table', 'Binary Search', 'Dynamic Programming', 'Memoization', 'Ordered Map', 'Suffix Array', 'Sorting', 'Kotlin']