Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 0d88d74

Browse files
2958. Length of Longest Subarray With at Most K Frequency
1 parent 74862c9 commit 0d88d74

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
class Solution {
2+
3+
// Solution by Sergey Leschev
4+
// 2958. Length of Longest Subarray With at Most K Frequency
5+
6+
// Sliding window
7+
// Time complexity: O(N)
8+
// Space complexity: O(N)
9+
10+
func maxSubarrayLength(_ nums: [Int], _ k: Int) -> Int {
11+
var freq = [Int: Int]()
12+
var ans = 0
13+
var i = 0
14+
15+
for j in 0..<nums.count {
16+
freq[nums[j], default: 0] += 1
17+
18+
while freq[nums[j], default: 0] > k {
19+
freq[nums[i], default: 0] -= 1
20+
i += 1
21+
}
22+
23+
ans = max(ans, j - i + 1)
24+
}
25+
26+
return ans
27+
}
28+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /