[LeetCode] Subarrays Distinct Element Sum of Squares I

2913. Subarrays Distinct Element Sum of Squares I

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int sumCounts(vector<int>& nums) {
int res = 0;
for(int i = 0; i < nums.size(); i++) {
unordered_set<int> us;
int sum = 0;
for(int j = i; j < nums.size(); j++) {
us.insert(nums[j]);
res += us.size() * us.size();
}
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/10/29/PS/LeetCode/subarrays-distinct-element-sum-of-squares-i/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.