Program to find frequency of the most frequent element in Python

PythonServer Side ProgrammingProgramming

Suppose we have an array nums and another value k. In one operation, we can select an index of nums and increase the element at that index by 1. We have to find the maximum possible frequency of an element after performing at most k number of operations.

So, if the input is like nums = [8,3,6], k = 9, then the output will be 3 because we can update 3 by 5, 6 by 2, to make it [8,8,8] so after 7 operations we have maximum frequency 3.

To solve this, we will follow these steps −

  • sort the list nums

  • left := 0, right := 1

  • while right < size of nums, do

    • k := k -(nums[right] - nums[right-1]) *(right - left)

    • if k < 0, then

      • k := k + nums[right] - nums[left]

      • left := left + 1

    • right := right + 1

  • return right - left

Example

Let us see the following implementation to get better understanding −

def solve(nums, k):
   nums.sort()
   left = 0
   right = 1

   while right < len(nums):
      k -= (nums[right] - nums[right-1]) * (right - left)

      if k < 0:
         k += nums[right] - nums[left]
         left += 1

      right += 1

   return right - left

nums = [8,3,6]
k = 9
print(solve(nums, k))

Input

[8,3,6], 9

Output

3
raja
Published on 07-Oct-2021 13:13:52
Advertisements