C++ set with comments
\nclass Solution {\npublic:\n    int sumImbalanceNumbers(vector<int>& nums) {\n        int ans = 0;\n        for (int i = 0; i < nums.size(); ++i) {\n          
```\nclass Solution {\npublic:\n    int sumImbalanceNumbers(vector<int>& nums) {\n        int ans = 0;\n        for (int i = 0; i < nums.size(); ++i) {\n            set<int> s;\n            int cur = 0;\n            for (int y = i; y < nums.size(); ++y) {\n                // if inserting nums[y] into s\n                // we have 4 possible situations\n                // 1: lower than any number\n                //     1.0: no other numbers exist\n                //     1.1: lower than previous lowest by 1\n                //     1.2: lower than previous lowest by > 1\n                // 2: in between 2 numbers\n                //     subtract 1 from cur\n                //     cur += difference from lower number > 1\n                //     cur += difference from higher number > 1\n                // 3: higher than any number, all scenarios similar to 1:\n                // 4: number already exists, do nothing\n                \n                if (s.insert(nums[y]).second) {  // Insert nums[y] into set s and check if it\'s a new insertion\n                    auto it = s.find(nums[y]);\n                    if (it == s.begin()) {  // Case 1: Lower than any number\n                        if (s.size() > 1 && *next(it) > nums[y] + 1) {\n                            cur++;  // Case 1.2\n                        }\n                    } else if (next(it) == s.end()) {  // Case 3: Higher than any number\n                        if (s.size() > 1 && *prev(it) < nums[y] - 1) {\n                            cur++;  // Case 3.2\n                        }\n                    } else {  // Case 2: In between two numbers\n                        if (*prev(it) < nums[y] - 1 && *next(it) > nums[y] + 1) {\n                            cur++;  // Case 2.2 and 2.3\n                        } else if (*prev(it) >= nums[y] - 1 && *next(it) <= nums[y] + 1) {\n                            cur--;  // Case 2.1\n                        }\n                    }\n                }\n                // Case 4: Number already exists, do nothing\n                \n                ans += cur;\n            }\n        }\n        return ans;\n    }\n};\n\n```
[]