C++ solution with comments
Intuition\nWe iterate all subarrays (double for loop) and track sorted elements in a multiset, updating our current imbalance as we go.\n\n# Code\n\nclass Solut
# Intuition\nWe iterate all subarrays (double for loop) and track sorted elements in a multiset, updating our current imbalance as we go.\n\n# Code\n```\nclass Solution {\npublic:\n    int sumImbalanceNumbers(vector<int>& nums) {\n        int count = 0;\n        \n        for (int j = 0; j < nums.size(); ++j) {\n            multiset<int> ms;\n            int imb = 0;\n            for (int i = j; i < nums.size(); ++i) {\n                auto it = ms.insert(nums[i]);\n                auto p = it != ms.begin() ? *prev(it) : -1;\n                auto n = next(it) != ms.end() ? *next(it) : -1;\n                \n                // We are first, nothing to do here\n                if (p == -1 && n == -1) {\n                \n                } \n                // We are smallest\n                else if (p == -1) {\n                    if (n-nums[i] > 1) {\n                        ++imb;\n                    }\n                }\n                // We are largest\n                else if (n == -1) {\n                    if (nums[i]-p > 1) {\n                        ++imb;\n                    }\n                }\n                // We are in the middle somewhere\n                else {\n                    if (n - p > 1) {\n                        // Adding nums[i] increases imbalance by 1\n                        if (n-nums[i] > 1 && nums[i]-p > 1) {\n                            ++imb;\n                        } \n                        // Or if it fits nicely, we decrease by 1\n                        else if (n-nums[i] <= 1 && nums[i]-p <= 1) {\n                            --imb;\n                        }\n                    }\n                }\n                count += imb;\n            }\n        }\n        \n        return count;\n    }\n};\n```
['C++']