- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find frequency of the most frequent element in Python
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