最大化子序列中严格大于其平均值的元素数量
给定一个包含正整数的大小为N的数组arr[] ,任务是找到可以使用任意数量的操作从数组中删除的最大元素数。在一个操作中,从给定数组中选择一个子序列,取它们的平均值并从数组中删除严格大于该平均值的数字。
例子:
Input: arr[] = {1, 1, 3, 2, 4}
Output: 3
Explanation:
Operation 1: Choose the subsequence {1, 2, 4}, average = (1+2+4)/3 = 2. So arr[5]=4 is deleted. arr[]={1, 1, 3, 2}
Operation 2: Choose the subsequence {1, 3, 2}, average = (1+3+2)/3 = 2. So arr[2]=3 is deleted. arr[]={1, 1, 2}
Operation 3: Choose the subsequence {1, 1}, average = (1+1)/2 = 1. So arr[3]=2 is deleted. arr[]={1, 1}
No further deletions can be performed.
Input: arr[] = {5, 5, 5}
Output: 0
方法:这个问题的问题是可以从数组中删除除最小元素之外的所有元素,因为如果只使用最小元素来创建子序列,那么它的平均值基本上是相同的元素,并且可以删除所有其他元素.现在要解决此问题,请按照以下步骤操作:
- 找到最小元素的频率,比如freq 。
- 返回N-freq作为这个问题的答案。
下面是上述方法的实现:
C++
// C++ code for the above approach
#include
using namespace std;
// Function to find the maximum number of
// elements that can be deleted from the array
int elementsDeleted(vector& arr)
{
// Size of the array
int N = arr.size();
// Minimum element
auto it = *min_element(arr.begin(), arr.end());
// Finding frequency of minimum element
int freq = 0;
for (auto x : arr) {
if (x == it)
freq++;
}
return N - freq;
}
// Driver Code
int main()
{
vector arr = { 3, 1, 1, 2, 4 };
cout << elementsDeleted(arr);
}
Java
// Java code for the above approach
import java.util.*;
class GFG{
// Function to find the maximum number of
// elements that can be deleted from the array
static int elementsDeleted(int []arr)
{
// Size of the array
int N = arr.length;
// Minimum element
int it = Arrays.stream(arr).min().getAsInt();
// Finding frequency of minimum element
int freq = 0;
for (int x : arr) {
if (x == it)
freq++;
}
return N - freq;
}
// Driver Code
public static void main(String[] args)
{
int []arr = { 3, 1, 1, 2, 4 };
System.out.print(elementsDeleted(arr));
}
}
// This code is contributed by 29AjayKumar
Python3
# Python code for the above approach
# Function to find the maximum number of
# elements that can be deleted from the array
def elementsDeleted(arr):
# Size of the array
N = len(arr)
# Minimum element
it = 10**9
for i in range(len(arr)):
it = min(it, arr[i])
# Finding frequency of minimum element
freq = 0
for x in arr:
if (x == it):
freq += 1
return N - freq
# Driver Code
arr = [3, 1, 1, 2, 4]
print(elementsDeleted(arr))
# This code is contributed by Saurabh jaiswal
C#
// C# code for the above approach
using System;
using System.Linq;
class GFG {
// Function to find the maximum number of
// elements that can be deleted from the array
static int elementsDeleted(int[] arr)
{
// Size of the array
int N = arr.Length;
// Minimum element
int it = arr.Min();
// Finding frequency of minimum element
int freq = 0;
foreach(int x in arr)
{
if (x == it)
freq++;
}
return N - freq;
}
// Driver Code
public static void Main(string[] args)
{
int[] arr = { 3, 1, 1, 2, 4 };
Console.WriteLine(elementsDeleted(arr));
}
}
// This code is contributed by ukasp.
Javascript
3
时间复杂度: O(N)
辅助空间: O(1)