Simple solution in C++, Java and Python
Intuition\nFor each subarray, the imbalance number is the number of "segments" (or we can call that consecutive integer ranges) - 1.\n\nSay if all numbers in th
# Intuition\nFor each subarray, the imbalance number is the number of "segments" (or we can call that consecutive integer ranges) - 1.\n\nSay if all numbers in the subarray are [1, 4, 4, 7, 3, 2, 9]\nThen after sorting (and dedup)\nThe ranges are [1, 4], [7, 7], [9, 9]. And the imbalance number is 3 - 1 = 2.\n\n\n# Approach\n1. Loop all the subarray start index i from 0 to n - 1.\n2. Maitnain a hashset s the particualr i.\n3. For each i <= j < n, \n(3.1) If nums[j] in s, then it\'s a duplicated number, the number of segments doesn\'t change.\n(3.2) If nums[j] is not in s, temporally increase the number of segments by 1. Namely, make itself as a new segment.\n(3.2.1) If nums[j] - 1 is in s, decrease the number of segments by one.\n(3.2.2) If nums[j] + 1 is in s, decrease the number of segments by one.\n4. Add the number of segments - 1 into final answer.\n5. Go to step 2 for other i values or return the final answer if all i values in [0, n - 1] are visited.\n\n# Complexity\n- Time complexity:\nO(n ^ 2)\n\n- Space complexity:\nO(n)\n\n# Code\nC++\n```\nclass Solution {\npublic:\n    int sumImbalanceNumbers(vector<int>& nums) {\n        const int n = nums.size();\n        int r = 0;\n        for (int i = 0; i < n; ++i) {\n            unordered_set<int> s;\n            int temp = -1;\n            for (int j = i; j < n; ++j) {\n                if (s.insert(nums[j]).second) {\n                    ++temp;\n                    temp -= s.count(nums[j] + 1) + s.count(nums[j] - 1);\n                }\n                r += temp;\n            }\n        }\n        return r;\n    }\n};\n```\n\nJava:\n```\nclass Solution {\n    public int sumImbalanceNumbers(int[] nums) {\n        int n = nums.length;\n        int r = 0;\n        for (int i = 0; i < n; ++i) {\n            Set<Integer> s = new HashSet<>();\n            int temp = -1;\n            for (int j = i; j < n; ++j) {\n                if (s.add(nums[j])) {\n                    temp += 1 - (s.contains(nums[j] + 1) ? 1 : 0) - (s.contains(nums[j] - 1) ? 1 : 0);\n                }\n                r += temp;\n            }\n        }\n        return r;\n    }\n}\n\n```\nPython\n```\nclass Solution:\n    def sumImbalanceNumbers(self, nums: List[int]) -> int:\n        n = len(nums)\n        r = 0\n        for i in range(n):\n            s = set()\n            temp = -1\n            for j in range(i, n):\n                if nums[j] not in s:\n                    s.add(nums[j])\n                    temp += 1 - (nums[j] + 1 in s) - (nums[j] - 1 in s)\n                r += temp\n        return r\n```\n
['Python', 'C++', 'Java', 'Python3']