给定一个由N 个整数和一个整数K组成的数组arr[] ,任务是找到最长子数组的长度,使得每个元素出现K次。
例子:
Input: arr[] = {3, 5, 2, 2, 4, 6, 4, 6, 5}, K = 2
Output: 8
Explanation: The subarray: {5, 2, 2, 4, 6, 4, 6, 5} of length 8 has frequency of every element as 2.
Input: arr[] = {5, 5, 5, 5}, K = 3
Output: 3
Explanation: The subarray: {5, 5, 5} of length 3 has frequency of every element as 3.
处理方法:按照以下步骤解决问题:
- 从给定数组生成所有可能的子数组。
- 对于每个子数组,初始化两个无序映射map1和map2 ,以存储每个元素的频率并存储具有相应频率的元素的计数。
- 如果对于任何子数组, map2的大小等于1并且当前元素的频率为K ,则意味着每个元素在当前子数组中单独出现K次。
- 最后,返回所有此类子数组的最大大小。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
// Function to find the length of
// required maximum subarray
int max_subarray_len(int arr[],
int N, int K)
{
// Initialize answer to 0
int ans = 0;
// Generate all subarrays having i as the
// starting index and j as the ending index
for (int i = 0; i < N; i++) {
// Stores frequency of subarray elements
unordered_map map1;
// Stores subarray elements with
// respective frequencies
unordered_map map2;
for (int j = i; j < N; j++) {
// Stores previous
// frequency of arr[j]
int prev_freq;
// If arr[j] hasn't
// occurred previously
if (map1.find(arr[j])
== map1.end()) {
// Set frequency as 0
prev_freq = 0;
}
else {
// Update previous frequency
prev_freq = map1[arr[j]];
}
// Increasing frequency
// of arr[j] by 1
map1[arr[j]]++;
// If frequency is stored
if (map2.find(prev_freq)
!= map2.end()) {
// If previous frequency is 1
if (map2[prev_freq] == 1) {
// Rove previous frequency
map2.erase(prev_freq);
}
else {
// Decrease previous frequency
map2[prev_freq]--;
}
}
int new_freq = prev_freq + 1;
// Increment new frequency
map2[new_freq]++;
// If updated frequency is equal to K
if (map2.size() == 1
&& (new_freq) == K) {
ans = max(
ans, j - i + 1);
}
}
}
// Return the maximum size
// of the subarray
return ans;
}
// Driver Code
int main()
{
// Given array arr[]
int arr[] = { 3, 5, 2, 2, 4,
6, 4, 6, 5 };
int K = 2;
// Size of Array
int N = sizeof(arr)
/ sizeof(arr[0]);
// Function Call
cout << max_subarray_len(
arr, N, K);
return 0;
}
Java
// Java program for the above approach
import java.util.*;
class GFG
{
// Function to find the length of
// required maximum subarray
static int max_subarray_len(int arr[],
int N, int K)
{
// Initialize answer to 0
int ans = 0;
// Generate all subarrays having i as the
// starting index and j as the ending index
for (int i = 0; i < N; i++)
{
// Stores frequency of subarray elements
HashMap map1 = new HashMap<>();
// Stores subarray elements with
// respective frequencies
HashMap map2 = new HashMap<>();
for (int j = i; j < N; j++)
{
// Stores previous
// frequency of arr[j]
int prev_freq = 0;
// If arr[j] hasn't
// occurred previously
if (!map1.containsKey(arr[j]))
{
// Set frequency as 0
prev_freq = 0;
}
else
{
// Update previous frequency
prev_freq = map1.get(arr[j]);
}
// Increasing frequency
// of arr[j] by 1
if(map1.containsKey(arr[j]))
{
map1.put(arr[j], map1.get(arr[j]) + 1);
}
else
{
map1.put(arr[j], 1);
}
// If frequency is stored
if (map2.containsKey(prev_freq))
{
// If previous frequency is 1
if (map2.get(prev_freq) == 1)
{
// Rove previous frequency
map2.remove(prev_freq);
}
else
{
// Decrease previous frequency
map2.put(prev_freq, map2.get(prev_freq)-1);
}
}
int new_freq = prev_freq + 1;
// Increment new frequency
if(map2.containsKey(new_freq))
{
map2.put(new_freq, map2.get(new_freq) + 1);
}
else{
map2.put(new_freq, 1);
}
// If updated frequency is equal to K
if (map2.size() == 1
&& (new_freq) == K) {
ans = Math.max(
ans, j - i + 1);
}
}
}
// Return the maximum size
// of the subarray
return ans;
}
// Driver Code
public static void main(String[] args)
{
// Given array arr[]
int arr[] = { 3, 5, 2, 2, 4,
6, 4, 6, 5 };
int K = 2;
// Size of Array
int N = arr.length;
// Function Call
System.out.print(max_subarray_len(
arr, N, K));
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 program for the above
# approach
from collections import defaultdict
# Function to find the length of
# required maximum subarray
def max_subarray_len(arr, N, K):
# Initialize answer to 0
ans = 0
# Generate all subarrays having
# i as the starting index and j
# as the ending index
for i in range(N):
# Stores frequency of subarray
# elements
map1 = defaultdict(int)
# Stores subarray elements with
# respective frequencies
map2 = defaultdict(int)
for j in range(i, N):
# If arr[j] hasn't
# occurred previously
if (arr[j] not in map1):
# Set frequency as 0
prev_freq = 0
else:
# Update previous frequency
prev_freq = map1[arr[j]]
# Increasing frequency
# of arr[j] by 1
map1[arr[j]] += 1
# If frequency is stored
if prev_freq in map2:
# If previous frequency is 1
if (map2[prev_freq] == 1):
# Rove previous frequency
del map2[prev_freq]
else:
# Decrease previous frequency
map2[prev_freq] -= 1
new_freq = prev_freq + 1
# Increment new frequency
map2[new_freq] += 1
# If updated frequency is equal
# to K
if (len(map2) == 1 and
(new_freq) == K):
ans = max(ans, j - i + 1)
# Return the maximum size
# of the subarray
return ans
# Driver Code
if __name__ == "__main__":
# Given array arr[]
arr = [3, 5, 2, 2, 4,
6, 4, 6, 5]
K = 2
# Size of Array
N = len(arr)
# Function Call
print(max_subarray_len(
arr, N, K))
# This code is contributed by Chitranayal
C#
// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG
{
// Function to find the length of
// required maximum subarray
static int max_subarray_len(int []arr,
int N, int K)
{
// Initialize answer to 0
int ans = 0;
// Generate all subarrays having i as the
// starting index and j as the ending index
for (int i = 0; i < N; i++)
{
// Stores frequency of subarray elements
Dictionary map1 = new Dictionary();
// Stores subarray elements with
// respective frequencies
Dictionary map2 = new Dictionary();
for (int j = i; j < N; j++)
{
// Stores previous
// frequency of arr[j]
int prev_freq = 0;
// If arr[j] hasn't
// occurred previously
if (!map1.ContainsKey(arr[j]))
{
// Set frequency as 0
prev_freq = 0;
}
else
{
// Update previous frequency
prev_freq = map1[arr[j]];
}
// Increasing frequency
// of arr[j] by 1
if(map1.ContainsKey(arr[j]))
{
map1[arr[j]] = map1[arr[j]] + 1;
}
else
{
map1.Add(arr[j], 1);
}
// If frequency is stored
if (map2.ContainsKey(prev_freq))
{
// If previous frequency is 1
if (map2[prev_freq] == 1)
{
// Rove previous frequency
map2.Remove(prev_freq);
}
else
{
// Decrease previous frequency
map2[prev_freq]= map2[prev_freq]-1;
}
}
int new_freq = prev_freq + 1;
// Increment new frequency
if(map2.ContainsKey(new_freq))
{
map2[new_freq] = map2[new_freq] + 1;
}
else{
map2.Add(new_freq, 1);
}
// If updated frequency is equal to K
if (map2.Count == 1
&& (new_freq) == K) {
ans = Math.Max(
ans, j - i + 1);
}
}
}
// Return the maximum size
// of the subarray
return ans;
}
// Driver Code
public static void Main(String[] args)
{
// Given array []arr
int []arr = { 3, 5, 2, 2, 4,
6, 4, 6, 5 };
int K = 2;
// Size of Array
int N = arr.Length;
// Function Call
Console.Write(max_subarray_len(
arr, N, K));
}
}
// This code is contributed by 29AjayKumar
Javascript
输出:
8
时间复杂度: O(N 2 )
辅助空间: O(N)
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。