October 21, 2024
Chicago 12, Melborne City, USA
java

Frequency of the most frequent element in an array (Leetcode)


Can you tell me why does this not work for all the TCs

class Solution {
  public int maxFrequency(int[] nums, int k) {
    Arrays.sort(nums);
    int maxFrequency = 1;
    for(int i=0;i<nums.length-1;i++)
    {
      int l = k;
      int currentMax = 1;
      for(int j=i+1;j<nums.length;j++)
      {
        int diff = Math.abs(nums[j] - nums[j-1]);
        if((diff*j) <= l)
        {
          currentMax++;
          l = l - (diff*j);
          maxFrequency = Math.max(currentMax, maxFrequency);
        }
      }
    }
    return maxFrequency;
  }
}

*My intuition is that beginning from the first element of the array, we make every element equal to its previous one.

Also, the below one is also quite similar but it works for all the TCs, the difference I could see is that the below one traverses the sorted array backwards

class Solution {
  public int maxFrequency(int[] nums, int k) {
    Arrays.sort(nums);
    int maxFrequency = 1;
    for(int i=nums.length-1;i>=0;i--)
    {
      int l = k;
      int currentMax = 1;
      for(int j=i-1;j>=0;j--)
      {
        int diff = nums[i] - nums[j];
        if(diff <= l)
        {
          currentMax++;
          l = l - diff;
          maxFrequency = Math.max(currentMax, maxFrequency);
        }
        else
          break;
      }
      if(maxFrequency >= i)
        break;
    }
    return maxFrequency;
  }
}



You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video