The Question:
You are given a 0-indexed integer array nums.
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 the squares of distinct counts of all subarrays of nums.
A subarray is a contiguous non-empty sequence of elements within an array.
This is the solution online since I wasn’t able to solve it myself but I don’t understand how it takes all the subarrays into consideration:
Solution:
int sumCounts(vector<int>& nums) {
int n = nums.size();
int result = 0;
for (int i = 0; i < n; i++) {
unordered_map<int, int> hash;
for (int j = i; j < n; j++) {
hash[nums[j]]++;
result += (hash.size() * hash.size());
}
}
return result;
}
for example: [1,2,1]
it considers:[1,2,1]
then: [2,1]
and then [1]
but what about [2]
and [1]
?
I’m very confused where I am going wrong. Kindly help me understand it.