Sponsored
Sponsored
Use these hints if you're stuck. Try solving on your own first.
Iterate over all subarrays in a nested fashion. Namely, for each left endpoint, start from nums[left] and add elements nums[left + 1], nums[left + 2], etc.
To keep track of the imbalance value, maintain a set of added elements.
Increment the imbalance value whenever a new number is not adjacent (+/- 1) to other old numbers. For example, when you add 3 to [1, 5], or when you add 5 to [1, 3]. For a formal proof, consider three cases: new value is (i) largest, (ii) smallest, (iii) between two old numbers.
Decrement the imbalance value whenever a new number is adjacent (+/- 1) to two old numbers. For example, when you add 3 to [2, 4]. The imbalance value does not change in the case of one adjacent old number.