给予N瓶。第i个瓶子的半径为A [i]。一旦将瓶子封闭在另一个瓶子中,就不再可见。任务是最大程度地减少可见瓶的数量。你可以把第i个瓶子到第j个瓶子,如果满足下面的条件。
例子:
Input :
8
1 1 2 3 4 5 5 4
Output :
2
Explanation:
1 -> 2 [1, 2, 3, 4, 5, 5, 4]
2 -> 3 [1, 3, 4, 5, 5, 4]
3 -> 4 [1, 4, 5, 5, 4]
4 -> 5 [1, 5, 5, 4]
1 -> 4 [5, 5, 4]
4 -> 5 [5, 5]
Finally, there are 2 bottles
left which are visible.
Hence the answer is 2.
方法:如果仔细观察,您会发现最小可见瓶子的数量将等于重复瓶子的最大数量。直觉是这样的,因为这些重复的瓶子无法装入单个较大的瓶子,因此我们至少需要与重复的瓶子数量一样多的较大瓶子。
下面是上述方法的实现:
C++
#include
using namespace std;
void min_visible_bottles(int* arr, int n)
{
map m;
int ans = 0;
for (int i = 0; i < n; i++) {
m[arr[i]]++;
ans = max(ans, m[arr[i]]);
}
cout << "Minimum number of "
<< "Visible Bottles are: "
<< ans << endl;
}
// Driver code
int main()
{
int n = 8;
int arr[] = { 1, 1, 2, 3, 4, 5, 5, 4 };
// Find the solution
min_visible_bottles(arr, n);
return 0;
}
Java
// Java code for the above approach
import java.util.*;
class GFG
{
static void min_visible_bottles(int[] arr, int n)
{
HashMap mp = new HashMap();
int ans = 0;
for (int i = 0; i < n; i++)
{
if (mp.containsKey(arr[i]))
{
mp.put(arr[i], mp.get(arr[i]) + 1);
}
else
{
mp.put(arr[i], 1);
}
ans = Math.max(ans, mp.get(arr[i]));
}
System.out.print("Minimum number of " +
"Visible Bottles are: " +
ans + "\n");
}
// Driver code
public static void main(String[] args)
{
int n = 8;
int arr[] = { 1, 1, 2, 3, 4, 5, 5, 4 };
// Find the solution
min_visible_bottles(arr, n);
}
}
// This code is contributed by Rajput-Ji
Python3
# Python3 code for the above approach
def min_visible_bottles(arr, n):
m = dict()
ans = 0
for i in range(n):
m[arr[i]] = m.get(arr[i], 0) + 1
ans = max(ans, m[arr[i]])
print("Minimum number of",
"Visible Bottles are: ", ans)
# Driver code
n = 8
arr = [1, 1, 2, 3, 4, 5, 5, 4]
# Find the solution
min_visible_bottles(arr, n)
# This code is contributed
# by Mohit Kumar
C#
// C# code for the above approach
using System;
using System.Collections.Generic;
class GFG
{
static void min_visible_bottles(int[] arr, int n)
{
Dictionary mp = new Dictionary();
int ans = 0;
for (int i = 0; i < n; i++)
{
if (mp.ContainsKey(arr[i]))
{
mp[arr[i]] = mp[arr[i]] + 1;
}
else
{
mp.Add(arr[i], 1);
}
ans = Math.Max(ans, mp[arr[i]]);
}
Console.Write("Minimum number of " +
"Visible Bottles are: " +
ans + "\n");
}
// Driver code
public static void Main(String[] args)
{
int n = 8;
int []arr = { 1, 1, 2, 3, 4, 5, 5, 4 };
// Find the solution
min_visible_bottles(arr, n);
}
}
// This code is contributed by Rajput-Ji
输出:
Minimum number of Visible Bottles are: 2