Input: nums =[2,3,1,4]Output: 3Explanation: There are 3 subarrays with non-zero**** imbalance numbers:- Subarray [3,1]with an imbalance number of 1.- Subarray [3,1,4]with an imbalance number of 1.- Subarray [1,4]with an imbalance number of 1.The imbalance number of all other subarrays is0. Hence, the sum of imbalance numbers of all the subarrays of nums is3.
Input: nums =[1,3,3,3,5]Output: 8Explanation: There are 7 subarrays with non-zero imbalance numbers:- Subarray [1,3]with an imbalance number of 1.- Subarray [1,3,3]with an imbalance number of 1.- Subarray [1,3,3,3]with an imbalance number of 1.- Subarray [1,3,3,3,5]with an imbalance number of 2.- Subarray [3,3,3,5]with an imbalance number of 1.- Subarray [3,3,5]with an imbalance number of 1.- Subarray [3,5]with an imbalance number of 1.The imbalance number of all other subarrays is0. Hence, the sum of imbalance numbers of all the subarrays of nums is8.
For each subarray, keep a set of seen numbers and track the imbalance as you extend the subarray. For each new number, update the imbalance by checking its neighbors. Since nums[i] <= n, use a boolean array for the set.
#include<vector>usingnamespace std;
classSolution {
public:int sumImbalanceNumbers(vector<int>& nums) {
int n = nums.size(), res =0;
for (int i =0; i < n; ++i) {
vector<bool> seen(n+2);
seen[nums[i]] = true;
int imb =0;
for (int j = i+1; j < n; ++j) {
int x = nums[j];
if (!seen[x]) {
if (!seen[x-1] &&!seen[x+1]) imb++;
if (seen[x-1] && seen[x+1]) imb--;
}
seen[x] = true;
res += imb;
}
}
return res;
}
};
classSolution {
publicintsumImbalanceNumbers(int[] nums) {
int n = nums.length, res = 0;
for (int i = 0; i < n; ++i) {
boolean[] seen =newboolean[n+2];
seen[nums[i]]=true;
int imb = 0;
for (int j = i+1; j < n; ++j) {
int x = nums[j];
if (!seen[x]) {
if (!seen[x-1]&&!seen[x+1]) imb++;
if (seen[x-1]&& seen[x+1]) imb--;
}
seen[x]=true;
res += imb;
}
}
return res;
}
}
classSolution {
funsumImbalanceNumbers(nums: IntArray): Int {
val n = nums.size
var res = 0for (i in0 until n) {
val seen = BooleanArray(n+2)
seen[nums[i]] = truevar imb = 0for (j in i+1 until n) {
val x = nums[j]
if (!seen[x]) {
if (!seen[x-1] && !seen[x+1]) imb++if (seen[x-1] && seen[x+1]) imb-- }
seen[x] = true res += imb
}
}
return res
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
classSolution:
defsumImbalanceNumbers(self, nums: list[int]) -> int:
n = len(nums)
res =0for i in range(n):
seen = [False] * (n+2)
seen[nums[i]] =True imb =0for j in range(i+1, n):
x = nums[j]
ifnot seen[x]:
ifnot seen[x-1] andnot seen[x+1]:
imb +=1if seen[x-1] and seen[x+1]:
imb -=1 seen[x] =True res += imb
return res