Leetcode 2465. Number of Distinct Averages
Given an integer array nums, move the elements of nums around to form a new array. Return the number of distinct averages you can get.
nums[i..j] from nums, then the average of nums[i..j] is the integer quotient of the sum of nums[i..j] divided by j-i+1.You cannot simply get the averages of all possible subarrays, as this would be too time-consuming.
nums guaranteed to be integers?
nums be negative?
nums can be negative.nums is empty?
nums is empty, we should return 0, as there are no elements to form any averages.nums.left) and one starting at the end (right) of the array.import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
public class Solution {
public int distinctAverages(int[] nums) {
Arrays.sort(nums);
Set<Double> averages = new HashSet<>();
int left = 0, right = nums.length - 1;
while (left < right) {
double avg = ((double) nums[left] + nums[right]) / 2;
averages.add(avg);
left++;
right--;
}
// If the array has an odd number of elements, handle the middle element
if (left == right) {
averages.add((double) nums[left]);
}
return averages.size();
}
}
O(n log n).O(n) since each element is processed exactly once.Overall, the time complexity of this solution is O(n log n) due to the sorting step.
Set which holds at most O(n/2) average values in the worst case.O(n).This approach ensures that we efficiently compute the number of distinct averages with a time complexity that is optimal for the problem constraints.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?