The distinct count of a subarray of nums is defined as:
Let nums[i..j] be a subarray of nums consisting of all the indices from i to j such that 0 <= i <= j < nums.length. Then the number of distinct values in nums[i..j] is called the distinct count of nums[i..j].
Return _the sum of thesquares of distinct counts of all subarrays of _nums.
A subarray is a contiguous non-empty sequence of elements within an array.
Input: nums =[1,2,1]Output: 15Explanation: Six possible subarrays are:[1]:1 distinct value
[2]:1 distinct value
[1]:1 distinct value
[1,2]:2 distinct values
[2,1]:2 distinct values
[1,2,1]:2 distinct values
The sum of the squares of the distinct counts in all subarrays is equal to 12+12+12+22+22+22=15.
Input: nums =[1,1]Output: 3Explanation: Three possible subarrays are:[1]:1 distinct value
[1]:1 distinct value
[1,1]:1 distinct value
The sum of the squares of the distinct counts in all subarrays is equal to 12+12+12=3.
#include<vector>#include<unordered_set>usingnamespace std;
classSolution {
public:int sumCounts(vector<int>& nums) {
int n = nums.size(), ans =0;
for (int l =0; l < n; ++l) {
unordered_set<int> s;
for (int r = l; r < n; ++r) {
s.insert(nums[r]);
ans += s.size() * s.size();
}
}
return ans;
}
};
1
2
3
4
5
6
7
8
9
10
11
12
funcsumCounts(nums []int) int {
n:= len(nums)
ans:=0forl:=0; l < n; l++ {
s:=map[int]bool{}
forr:=l; r < n; r++ {
s[nums[r]] = trueans+= len(s) * len(s)
}
}
returnans}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
import java.util.*;
classSolution {
publicintsumCounts(int[] nums) {
int n = nums.length, ans = 0;
for (int l = 0; l < n; ++l) {
Set<Integer> s =new HashSet<>();
for (int r = l; r < n; ++r) {
s.add(nums[r]);
ans += s.size() * s.size();
}
}
return ans;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
funsumCounts(nums: IntArray): Int {
val n = nums.size
var ans = 0for (l in0 until n) {
val s = mutableSetOf<Int>()
for (r in l until n) {
s.add(nums[r])
ans += s.size * s.size
}
}
return ans
}
1
2
3
4
5
6
7
8
9
defsumCounts(nums):
n = len(nums)
ans =0for l in range(n):
s = set()
for r in range(l, n):
s.add(nums[r])
ans += len(s) * len(s)
return ans
1
2
3
4
5
6
7
8
9
10
11
12
13
use std::collections::HashSet;
pubfnsum_counts(nums: Vec<i32>) -> i32 {
let n = nums.len();
letmut ans =0;
for l in0..n {
letmut s = HashSet::new();
for r in l..n {
s.insert(nums[r]);
ans += (s.len() * s.len()) asi32;
}
}
ans
}