Skip to content

Commit

Permalink
Add a solution to the Frequency of the Most Frequent Element
Browse files Browse the repository at this point in the history
  • Loading branch information
soapyigu committed Oct 6, 2022
1 parent c712ca0 commit 264d2ab
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 5 deletions.
27 changes: 27 additions & 0 deletions SlidingWindow/FrequencyMostFrequentElement.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
/**
* Question Link: https://leetcode.com/problems/frequency-of-the-most-frequent-element/
* Primary idea: Slding window, sort the nums and move left if k cannot make current window even.
*
* Time Complexity: O(nlogn), Space Complexity: O(1)
*
*/

class FrequencyMostFrequentElement {
func maxFrequency(_ nums: [Int], _ k: Int) -> Int {
let nums = nums.sorted()
var left = 0, res = 1, sum = 0

for (i, num) in nums.enumerated() {
sum += num

while (i - left + 1) * num - sum > k {
sum -= nums[left]
left += 1
}

res = max(res, i - left + 1)
}

return res
}
}
10 changes: 5 additions & 5 deletions SlidingWindow/LongestContinuousSubarrayLimit.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/**
* Question Link: https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/description/
* Question Link: https://leetcode.com/problems/longest-continuous-subarray-with-absolute-diff-less-than-or-equal-to-limit/
* Primary idea: Slding window, use max and min queues to track largest difference along the way. Move left pointer to get the potential result.
*
* Note: k may be invalid, mention that with interviewer
Expand All @@ -9,7 +9,7 @@

class LongestContinuousSubarrayLimit {
func longestSubarray(_ nums: [Int], _ limit: Int) -> Int {
var maxQueue = [Int](), minQueue = [Int](), left = 0, size = 0
var maxQueue = [Int](), minQueue = [Int](), left = 0, res = 0

for (i, num) in nums.enumerated() {
while !maxQueue.isEmpty && maxQueue.last! < num {
Expand All @@ -33,9 +33,9 @@ class LongestContinuousSubarrayLimit {
left += 1
}

size = max(size, i - left + 1)
res = max(res, i - left + 1)
}

return size
return res
}
}
}

0 comments on commit 264d2ab

Please sign in to comment.