1014. Imbalance Total
A choir director studies nums, the pitch ratings of n singers in a line. For any contiguous group of singers, sort its ratings (equal ratings stay as separate entries) and count the neighbouring pairs in that sorted order whose difference is strictly greater than 1. That count is the group's imbalance.
Return the sum of the imbalance over every non-empty contiguous group (every subarray), modulo 1000000007.
A fast solution counts contributions per value instead of sorting each group, in about O(n log n) time and O(n) space.
Example 1
- Input:
- nums = [8,2,6,3,6]
- Output:
- 13
- Explanation:
Out of the 15 subarrays, the ones with a gap larger than 1 between sorted neighbours add up to a total imbalance of 13 (for example [8,2,6] sorts to 2,6,8 with two gaps).
Example 2
- Input:
- nums = [5,5,5]
- Output:
- 0
- Explanation:
Every subarray contains only the value 5, so there is no gap anywhere and the total is 0.
Constraints
1 ≤ n ≤ 105
1 ≤ nums[i] ≤ 109
Return the total modulo 1000000007.
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)