Skip to content

Commit

Permalink
Create: 1838-frequency-of-the-most-frequent-element.rs / .go
Browse files Browse the repository at this point in the history
  • Loading branch information
AkifhanIlgaz committed Jan 13, 2023
1 parent ee7a3bc commit 497156e
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
24 changes: 24 additions & 0 deletions go/1838-frequency-of-the-most-frequent-element.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import (
"math"
"sort"
)

func maxFrequency(nums []int, k int) int {
sort.Ints(nums)

left, right, res, total := 0,0,0,0

for right < len(nums) {
total += nums[right]

for nums[right] * (right - left +1) > total + k {
total -= nums[left]
left++
}

res = int(math.Max(float64(res), float64(right - left + 1)))
right++
}

return res
}
21 changes: 21 additions & 0 deletions rust/1838-frequency-of-the-most-frequent-element.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
impl Solution {
pub fn max_frequency(mut nums: Vec<i32>, k: i32) -> i32 {
let (mut left, mut right, mut res, mut total) = (0, 0, 0, 0);

nums.sort_unstable();

while right < nums.len() {
total += nums[right];

while (nums[right] * (right - left + 1) as i32) - total > k {
total -= nums[left];
left += 1;
}

res = res.max(right - left + 1);
right += 1;
}

res as i32
}
}

0 comments on commit 497156e

Please sign in to comment.