Suppose we have a list of numbers called nums and another value k. Let us consider an operation where we increase some element by one. We can perform at most k times, we have to find the value of the most frequently occurring number we can obtain. If there are more than one solution, select the smallest possible number.
So, if the input is like nums = [1, 0, 0, 0, 8, 8, 8, 8] k = 8, then the output will be 8, as we can increase 1, 7 times to get 8, and increase any 0 to 1, so, we get [8, 1, 0, 0, 8, 8, 8, 8]. So the result is 8.
To solve this, we will follow these steps:
Let us see the following implementation to get better understanding:
class Solution: def solve(self, nums, k): nums.sort() low, high = 0, 0 dist = 0 best = 0 ret = -1 while high < len(nums): if high > 0 and nums[high] != nums[high - 1]: dist += (high - low) * (nums[high] - nums[high - 1]) high += 1 while dist > k: dist -= nums[high - 1] - nums[low] low += 1 if high - low > best: best = high - low ret = nums[high - 1] return ret ob = Solution() nums = [1, 0, 0, 0, 8, 8, 8, 8] k = 8 print(ob.solve(nums, k))
[1, 0, 0, 0, 8, 8, 8, 8], 8
8