最大化给定数组中大小为 K 的子序列中不同元素的计数
给定一个包含N个整数的数组arr[]和一个整数K ,任务是找到K个整数的所有子序列中不同元素的最大计数。
例子:
Input: arr[]={1, 1, 2, 2}, K=3
Output: 2
Explanation: The subsequence {1, 1, 2} has 3 integers and the number of distinct integers in it are 2 which is the maximum possible. Other possible subsequence is {1, 2, 2}.
Input: arr[]={1, 2, 3, 4}, K=3
Output: 3
方法:给定的问题可以使用贪婪的方法来解决,通过观察所需的答案是给定数组或 K 中唯一元素的计数的最小值。现在,要解决这个问题,请按照以下步骤操作:
- 创建一个集合S ,它存储数组arr[]中存在的不同整数。
- 遍历数组arr[]并将每个数字插入集合S中。
- 返回K的最小值和S的大小,这是所需的答案。
下面是上述方法的实现:
C++
// C++ code for the above approach
#include
using namespace std;
// Function to find count of maximum
// distinct elements in a subsequence
// of size K of the given array arr[]
int maxUnique(vector& arr, int K)
{
// Set data structure to
// store the unique elements
unordered_set S;
// Loop to traverse the given array
for (auto x : arr) {
// Insert into the set
S.insert(x);
}
// Returning the minimum out of the two
return min(K, (int)S.size());
}
// Driver Code
int main()
{
vector arr = { 1, 1, 2, 2 };
int K = 3;
cout << maxUnique(arr, K);
}
Java
// Java code for the above approach
import java.util.*;
class GFG{
// Function to find count of maximum
// distinct elements in a subsequence
// of size K of the given array arr[]
static int maxUnique(int []arr, int K)
{
// Set data structure to
// store the unique elements
HashSet S = new HashSet();
// Loop to traverse the given array
for (int x : arr) {
// Insert into the set
S.add(x);
}
// Returning the minimum out of the two
return Math.min(K, (int)S.size());
}
// Driver Code
public static void main(String[] args)
{
int[] arr = { 1, 1, 2, 2 };
int K = 3;
System.out.print(maxUnique(arr, K));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python Program to implement
# the above approach
# Function to find count of maximum
# distinct elements in a subsequence
# of size K of the given array arr[]
def maxUnique(arr, K):
# Set data structure to
# store the unique elements
S = set()
# Loop to traverse the given array
for x in arr:
# Insert into the set
S.add(x)
# Returning the minimum out of the two
return min(K, len(S))
# Driver Code
arr = [1, 1, 2, 2]
K = 3
print(maxUnique(arr, K))
# This code is contributed by gfgking
C#
// C# implementation for the above approach
using System;
using System.Collections;
using System.Collections.Generic;
class GFG
{
// Function to find count of maximum
// distinct elements in a subsequence
// of size K of the given array arr[]
static int maxUnique(int []arr, int K)
{
// Set data structure to
// store the unique elements
HashSet S = new HashSet();
// Loop to traverse the given array
foreach (int x in arr) {
// Insert into the set
S.Add(x);
}
// Returning the minimum out of the two
return Math.Min(K, (int)S.Count);
}
// Driver Code
public static void Main()
{
int []arr = { 1, 1, 2, 2 };
int K = 3;
Console.Write(maxUnique(arr, K));
}
}
// This code is contributed by Samim Hossain Mondal.
Javascript
输出
2
时间复杂度: O(N)
辅助空间: O(N)