Sponsored
Sponsored
Use a sliding window technique to find the longest subarray that satisfies the condition where no element occurs more than k
times. You can maintain a frequency map that tracks the count of each element in the current window.
Time Complexity: O(n)
where n
is the number of elements in nums
, as each index is visited at most twice.
Space Complexity: O(m)
, where m
is the maximum element value in nums
representing the size of the frequency array.
1function longestGoodSubarray(nums, k) {
2 let freq = new Map();
3 let start = 0, max_len = 0;
4
5 for (let end = 0; end < nums.length; end++) {
6 freq.set(nums[end], (freq.get(nums[end]) || 0) + 1);
7
8 while (freq.get(nums[end]) > k) {
9 freq.set(nums[start], freq.get(nums[start]) - 1);
10 if (freq.get(nums[start]) === 0) {
11 freq.delete(nums[start]);
12 }
13 start++;
14 }
15
16 max_len = Math.max(max_len, end - start + 1);
17 }
18
19 return max_len;
20}
21
22const nums = [1, 2, 3, 1, 2, 3, 1, 2];
23const k = 2;
24console.log(longestGoodSubarray(nums, k));
This JavaScript function uses a Map
to maintain element frequencies during window traversal. The sliding window approach is employed by dynamically adjusting the start
pointer and measuring the maximum valid subarray length concurrently.
A different approach is to use binary search to determine the maximum subarray length. The problem translates to searching for the maximum length for which a good subarray exists, using a helper function that verifies subarray validity in O(n)
time.
Time Complexity: O(n log n)
due to the binary search layers and inner check iteration.
Space Complexity: O(m)
for the frequency array, where m
is the maximum element value.
using System.Collections.Generic;
class Program {
public static bool IsGoodSubarray(int[] nums, int subarraySize, int k) {
Dictionary<int, int> freq = new Dictionary<int, int>();
for (int i = 0; i < subarraySize; i++) {
if (!freq.ContainsKey(nums[i])) freq[nums[i]] = 0;
freq[nums[i]]++;
if (freq[nums[i]] > k) return false;
}
for (int i = subarraySize; i < nums.Length; i++) {
if (!freq.ContainsKey(nums[i])) freq[nums[i]] = 0;
freq[nums[i]]++;
if (freq[nums[i]] > k) return false;
freq[nums[i - subarraySize]]--;
if (freq[nums[i - subarraySize]] == 0) freq.Remove(nums[i - subarraySize]);
}
return true;
}
public static int LongestGoodSubarray(int[] nums, int k) {
int low = 1, high = nums.Length, answer = 0;
while (low <= high) {
int mid = low + (high - low) / 2;
if (IsGoodSubarray(nums, mid, k)) {
answer = mid;
low = mid + 1;
} else {
high = mid - 1;
}
}
return answer;
}
static void Main() {
int[] nums = {1, 2, 3, 1, 2, 3, 1, 2};
int k = 2;
Console.WriteLine(LongestGoodSubarray(nums, k));
}
}
This C# program deploys a binary search to pinpoint the longest subarray satisfying the condition. The determination of subarray validity at each candidate length is done through a secondary helper function, which validates the current window behavior.