'LeetCode Java - Frequency of the most frequent element
So I was trying to solve the LeetCode question n.1838 (Frequency of the most frequent element) and it works except for a test case with an input array of 500000 elements (1 <= nums.length <= 10^5): it gives me TimeLimitExceeded and I don't understand why. I tried to explain my approach with comments in the code, but it's very easy: I sort the array first so I can start from the last element (the bigger one), I loop the array and for each element in the array i calculate the frequency for different cases:
- if nums[i] == nums[i - 1] increment the frequency
- if k < nums[i] - nums[i - 1] there's no need to do anything, so i just update j to get outside of the loop
- else I add to nums[i - 1] the difference so it can be nums[i], I update q and num.
I then update the max frequency and once I'm outside the while loop I do the same for each element of the array.
Here's my method:
public int maxFrequency(int[] nums, int k) {
//corner case
if (nums.length == 1)
return 1;
//order array
Arrays.sort(nums);
int max = 0;
int freq = 0;
int num = 0; //will always be the int at the index - j (j will be incremented each time)
int j = 0;
//start from the last element of the array
for (int i = nums.length - 1; i >= 0; i--) {
num = nums[i - j];
int q = k;
while (q >= 0 && i - j >= 0) {
//if element equals itself, increment frequency
if (nums[i] - num == 0) {
freq++;
j++;
} // if k < nums[i] - num (aka even if we add k to num we won't have a new nums[i])
else if (nums[i] - num > q) {
j = i + 1; //to get out of the while loop
} else { //case where i can add k because k >= nums[i] - num
q -= nums[i] - num;
freq++;
j++;
} // update num only if i - j > 0 so we dont have ArrayOutOfBoundException
if (i - j >= 0) {
num = nums[i - j];
} //update max frequency
max = Math.max(freq, max);
}
freq = 0;
j = 0;
}
return max;
}
Any advice or hint would be helpful, thanks in advance.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
