Video Explanation (2 Approaches - N*N and N)
Explanation\n\nClick here for the video\n\n# Code\n\nclass Solution {\npublic:\n    /*\n    int sumImbalanceNumbers(vector<int>& nums) {\n        int n = nums.s
# Explanation\n\n[Click here for the video](https://youtu.be/Ec67Jgw22uE)\n\n# Code\n```\nclass Solution {\npublic:\n    /*\n    int sumImbalanceNumbers(vector<int>& nums) {\n        int n = nums.size();\n        int result = 0;\n        \n        for (int l = 0; l < n; l ++) {\n            unordered_set<int> s;\n            s.insert(nums[l]);\n            int good_pair = 0;\n            \n            for (int r = l+1; r < n; r ++) {\n                if (!s.count(nums[r])) {\n                    good_pair += 1 - (s.count(nums[r] - 1) > 0) - (s.count(nums[r] + 1) > 0);  \n                }\n                result += good_pair;\n                \n                s.insert(nums[r]);\n            }\n        }\n        return result;\n    }\n    */\n    \n    int sumImbalanceNumbers(vector<int>& nums) {\n        int n = nums.size();\n        int result = 0;\n        \n        unordered_map<int, int> pos;\n        vector<int> prefix(n+2, 0);\n        \n        for (int l = 0; l < n; l ++) {\n            int eq_till = pos[nums[l]];\n\n            prefix[eq_till + 1] += (n - l);\n            prefix[l+1] -= (n - l);\n            \n            int minus_one_till = pos[nums[l] - 1];\n            int plus_one_till  = pos[nums[l] + 1];\n            \n            if (minus_one_till > eq_till) {\n                prefix[eq_till+1] -= (n - l);\n                prefix[minus_one_till+1] += (n - l);\n            }\n            if (plus_one_till > eq_till) {\n                prefix[eq_till+1] -= (n - l);\n                prefix[plus_one_till+1] += (n - l);\n            }\n           \n            pos[nums[l]] = l+1;\n        }\n        \n        for (int j = 1; j <= n; j ++) {\n            prefix[j] += prefix[j-1];\n            result += prefix[j];\n        }\n                \n        return result;\n    }\n};\n```
['C++']