My Solution
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:\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```\nclass Solution {\n public:\n  // If sorted(nums)[i + 1] - sorted(nums)[i] > 1, then there\'s a gap. Instead\n  // of determining the number of gaps in each subarray, let\'s find out how many\n  // subarrays contain each gap.\n  int sumImbalanceNumbers(vector<int>& nums) {\n    const int n = nums.size();\n    int ans = 0;\n    // Note that to avoid double counting, only `left` needs to check nums[i].\n    // This adjustment ensures that i represents the position of the leftmost\n    // element of nums[i] within the subarray.\n\n    // left[i] := max index l s.t. nums[l] = nums[i] or nums[i] + 1\n    vector<int> left(n);\n    // right[i] := min index r s.t. nums[r] = nums[i]\n    vector<int> right(n);\n\n    vector<int> numToIndex(n + 2, -1);\n    for (int i = 0; i < n; ++i) {\n      left[i] = max(numToIndex[nums[i]], numToIndex[nums[i] + 1]);\n      numToIndex[nums[i]] = i;\n    }\n\n    fill(numToIndex.begin(), numToIndex.end(), n);\n    for (int i = n - 1; i >= 0; --i) {\n      right[i] = numToIndex[nums[i] + 1];\n      numToIndex[nums[i]] = i;\n    }\n\n    // The gap above nums[i] persists until encountering nums[i] or nums[i] + 1.\n    // Consider subarrays nums[l..r] with l <= i <= r, where l in [left[i], i]\n    // and r in [i, right[i] - 1]. There are (i - left[i]) * (right[i] - i)\n    // subarrays satisfying this condition.\n    for (int i = 0; i < n; ++i)\n      ans += (i - left[i]) * (right[i] - i);\n\n    // Subtract n * (n + 1) / 2 to account for the overcounting of elements\n    // initially assumed to have a gap. This adjustment is necessary as the\n    // maximum element of every subarray does not have a gap.\n    return ans - n * (n + 1) / 2;\n  }\n};\n\n```
['C++']