forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create: 1838-frequency-of-the-most-frequent-element.rs / .go
- Loading branch information
1 parent
ee7a3bc
commit 497156e
Showing
2 changed files
with
45 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} | ||
} |