using
System;
using
System.Collections.Generic;
using
System.Linq;
class
GFG{
static
bool
IsValid(List<
int
> A)
{
int
mins = A.Max() + 1;
int
maxs = -1;
for
(
int
i = 0; i < A.Count; i++)
{
mins = Math.Min(mins, A[i]);
maxs = Math.Max(maxs, A[i]);
if
(A[i] != mins && A[i] != maxs)
return
false
;
}
return
true
;
}
static
int
CountTotalValidPermutations(List<
int
> S)
{
HashSet<List<
int
>> distinctPermutations =
new
HashSet<List<
int
>>(
new
ListComparer<
int
>());
S.Sort();
do
{
distinctPermutations.Add(
new
List<
int
>(S));
}
while
(NextPermutation(S));
int
count = 0;
foreach
(List<
int
> A
in
distinctPermutations)
{
if
(IsValid(A))
count++;
}
return
count;
}
static
bool
NextPermutation(List<
int
> list)
{
int
i = list.Count - 2;
while
(i >= 0 && list[i] >= list[i + 1])
i--;
if
(i < 0)
return
false
;
int
j = list.Count - 1;
while
(list[j] <= list[i])
j--;
int
temp = list[i];
list[i] = list[j];
list[j] = temp;
j = list.Count - 1;
i++;
while
(i < j)
{
temp = list[i];
list[i] = list[j];
list[j] = temp;
i++;
j--;
}
return
true
;
}
class
ListComparer<T> : IEqualityComparer<List<T>>
{
public
bool
Equals(List<T> x, List<T> y)
{
return
x.SequenceEqual(y);
}
public
int
GetHashCode(List<T> obj)
{
return
obj.Sum(item => item.GetHashCode());
}
}
static
void
Main()
{
List<
int
> S1 =
new
List<
int
> { 3, 6, 9 };
Console.WriteLine(CountTotalValidPermutations(S1));
List<
int
> S2 =
new
List<
int
> { 7, 8 };
Console.WriteLine(CountTotalValidPermutations(S2));
List<
int
> S3 =
new
List<
int
> { 2, 1, 3, 1 };
Console.WriteLine(CountTotalValidPermutations(S3));
}
}