Apply Operations to Maximize Frequency Score — LeetCode 2968 Python Solution
- Problem
- #2968
- Pattern
- Sliding Window
- Reading time
- 4 min
- Source
- leetcode.com
The problem
You are given a 0-indexed integer array nums and an integer k. You can perform the following operation on the array at most k times: Choose any index i from the array and increase or decrease nums[i] by 1.
Example
- Input
- nums = [1,2,6,4], k = 3
- Output
- 3
- Explanation
- We can do the following operations on the array:
Python solution
class Solution:
def maxFrequencyScore(self, nums: List[int], k: int) -> int:
nums.sort()
s = list(accumulate(nums, initial=0))
n = len(nums)
l, r = 0, n
while l < r:
mid = (l + r + 1) >> 1
ok = False
for i in range(n - mid + 1):
j = i + mid
x = nums[(i + j) // 2]
left = ((i + j) // 2 - i) * x - (s[(i + j) // 2] - s[i])
right = (s[j] - s[(i + j) // 2]) - ((j - (i + j) // 2) * x)
if left + right <= k:
ok = True
break
if ok:
l = mid
else:
r = mid - 1
return lComplexity
| Measure | Complexity |
|---|---|
| Time | O(n \times \log n) |
| Space | O(n) auxiliary |
Pattern: Sliding Window
Collapse a nested loop over every subarray into a single pass with two indices. LeetCode 2968. Apply Operations to Maximize Frequency Score is filed here because LeetCode tags it Sliding Window, which is the vocabulary this hub collects.
The sliding window guide has the Python template for the pattern and the 116 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2968. Apply Operations to Maximize Frequency Score?
- LeetCode 2968. Apply Operations to Maximize Frequency Score is rated Hard on LeetCode.
- What is the time complexity of LeetCode 2968. Apply Operations to Maximize Frequency Score?
- The Python solution on this page runs in O(n \times \log n).
- What is the space complexity of LeetCode 2968. Apply Operations to Maximize Frequency Score?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 2968. Apply Operations to Maximize Frequency Score cover?
- LeetCode 2968. Apply Operations to Maximize Frequency Score is tagged Array, Binary Search, Prefix Sum, Sorting and Sliding Window on LeetCode.