LeetCode 2913: Subarrays Distinct Element Sum of Squares I
Problem Description
Explanation:
To solve this problem, we can iterate through all possible subarrays of the given array nums
. For each subarray, we calculate the distinct count of elements in that subarray and then square that count. Finally, we sum up the squares of distinct counts for all subarrays to get the result.
Algorithm:
- Initialize a variable
result
to store the final result. - Iterate over all possible subarrays using two nested loops.
- For each subarray, calculate the distinct count of elements.
- Square the distinct count and add it to the
result
. - Return the
result
as the final answer.
Time Complexity: O(n^3), where n is the length of the input array nums
.
Space Complexity: O(1) since we are not using any extra space.
:
Solutions
class Solution {
public int sumOfSquares(int[] nums) {
int result = 0;
for (int i = 0; i < nums.length; i++) {
for (int j = i; j < nums.length; j++) {
int distinctCount = countDistinct(nums, i, j);
result += distinctCount * distinctCount;
}
}
return result;
}
private int countDistinct(int[] nums, int start, int end) {
Set<Integer> set = new HashSet<>();
for (int i = start; i <= end; i++) {
set.add(nums[i]);
}
return set.size();
}
}
Loading editor...