C++ | Set | O(n^2logn)
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n^2 logn)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\nclass Solution {\n\n\npublic:\n    int sumImbalanceNumbers(vector<int>& nums) {\n        int n = nums.size(), ans = 0;\n        const int _inf = -1000, inf = 1e9;\n\t\tfor (int i = 0; i < n; i++) {\n\t\t\tset<int> st;\n            int cnt = 0;\n            // j is the end of subarray starting at i for which we calculate imbalance\n\t\t\tfor (int j = i; j < n; j++) {\n\t\t\t\tauto it = st.lower_bound(nums[j]);\n                // if already in set, do nothing.\n                if (it != st.end() && *it == nums[j]) {\n                    ans += cnt;\n                    continue;\n                }\n\n                // element just lesser , element just greater than nums[j]\n                int l = _inf, r = inf ;\n\t\t\t\tif (it == st.end() && it != st.begin()) {\n\t\t\t\t\tl = *(--it);\n\t\t\t\t} else if (it != st.end()){\n\t\t\t\t\tr = *it;\n                    if (it != st.begin()) {\n                        l = *(--it);\n                    }\n\t\t\t\t}\n\n                // remove existing pair [l, r] if diff was > 1\n                if (l != _inf && r != inf && r - l > 1) {\n                    cnt--;\n                }\n\n                // add new pairs due to nums[j]\n                if (nums[j] > l + 1 && l != _inf) {\n                    cnt++;\n                }\n\n                // add new pairs due to nums[j]\n                if (nums[j] < r - 1 && r != inf) {\n                    cnt++;\n                }\n\n                st.insert(nums[j]);\n                ans += cnt;\n\t\t\t}\n\t\t}\n\t\treturn ans;\n    }\n};\n\n```
['C++']