Sum of Imbalance Number of All Subarrays
Intuitiongiven a 3 number group a, b, c where a < b < c it can be proved that the group (a c) would have an imbalance of 1 (Because c is at least +2 bigger than
# Intuition
given a 3 number group a, b, c where a < b < c it can be proved that the group (a c) would have an imbalance of 1 (Because c is at least +2 bigger than a)
Keeping b between a and c could either remove the imbalance e.g 1 2 3, do nothing to the imbalance e.g 1 4 5 or add 1 to the imbalance e.g 1 3 5

# Approach
The first thing I did was eliminate the edge case

Edge Case 1: a b and c are not unique
In this case I just skipped it since 1 3 and 1 3 3 or 1 1 3 have the same imbalance

Edge Case 2: a or c does not exist
If the new number b appears at the end or beginning of the sorted array then it won't have anything after or before it. In those cases I checked if adding it to behind the max or in front of the min would cause an imbalance and added it

As an example if 4 is the least and 2 was added to the array the imbalance will be increase by 1 and the sorted array will look something like this 2, 4, ...

Considering we have made sure a b and c are different we can check to see if the number b-1 exists to see if we have an imbalance in group a b and c-1 for b c

With the edge cases out we can get into the good part

We have already established group a c where a > b > c has an imbalance of 1

We could create new groups a b and b c to replace group a c where a b replaces a c and b c is a new group

So if a b does not have an imbalance we subtract one since a c had one and if a b has an imbalance we do nothing for the same reason

Likewise if b c has an imbalance we add 1 since b c is a new group that didn't exist before but if b c has no imbalance we do nothing for the same reason as stated before

# Complexity
# Time complexity:
O(n∗n)

# Space complexity:
O(n)
# Code
```javascript []
/**
 * @param {number[]} nums
 * @return {number}
 */

var sumImbalanceNumbers = function(nums) {
  let ans = 0
  for(let i = 0; i < nums.length-1; i++){
    const set = new Set([nums[i]])
    let max = nums[i], min = nums[i], imbalance = 0
    for(let j = i+1; j < nums.length; j++){
      if(!set.has(nums[j])){
        if(max < nums[j]){
          if(nums[j] > max+1)imbalance++
          max = nums[j]
        }else if(min > nums[j]){
          if(nums[j] < min-1)imbalance++
          min = nums[j]
        }else{
          if(set.has(nums[j]-1))imbalance--
          if(!set.has(nums[j]+1))imbalance++
        }
        set.add(nums[j])
      }
      ans += imbalance
    }
  }
  return ans
};
```
['JavaScript']