给定两个整数N和M ,任务是查找元素范围为[1,M]的大小为N的数组的数目,在其中可以通过替换少于一半的元素来使长度大于1的所有子数组回文即floor(length / 2) 。
例子:
Input: N = 2, M = 3
Output: 6
Explanation:
There are 9 arrays possible of length 2 using values 1 to 3 i.e. [1, 1], [1, 2], [1, 3], [2, 1][2, 2], [2, 3], [3, 1], [3, 2], [3, 3].
All of these arrays except [1, 1], [2, 2] and [3, 3] have subarrays of length greater than 1 which requires 1 operation to make them palindrome. So the required answer is 9 – 3 = 6.
Input: N = 5, M = 10
Output: 30240
方法:可以根据以下观察结果解决问题:
- 使数组成为回文区所需的最大允许操作数可能是floor(size(array)/ 2) 。
- 可以看出,通过选择一个以相同值开始和结束的子数组,使其成为回文集所需的操作次数将小于floor(subarray的大小)/ 2 。
- 因此,任务减少为使用[1,M]范围内的整数值找到大小为N的数组的数量,该整数值不包含任何重复元素,这可以通过找到M与N的置换即Mp来轻松完成。 N ,等于M *(M – 1)*(M – 2)*…*(M – N +1)。
请按照以下步骤解决问题:
- 初始化一个整数变量,例如ans = 1 。
- 从i = 0遍历到N – 1,并将ans更新为ans = ans *(Mi)
- 打印ans作为答案。
下面是上述方法的实现:
C++
// C++ program for the above approach
#include
using namespace std;
typedef long long ll;
// Function to find the number of arrays
// following the given condition
void noOfArraysPossible(ll N, ll M)
{
// Initialize answer
ll ans = 1;
// Calculate nPm
for (ll i = 0; i < N; ++i) {
ans = ans * (M - i);
}
// Print ans
cout << ans;
}
// Driver Code
int main()
{
// Given N and M
ll N = 2, M = 3;
// Function Call
noOfArraysPossible(N, M);
return 0;
}
Java
// Java program for the above approach
class GFG
{
// Function to find the number of arrays
// following the given condition
static void noOfArraysPossible(int N, int M)
{
// Initialize answer
int ans = 1;
// Calculate nPm
for (int i = 0; i < N; ++i)
{
ans = ans * (M - i);
}
// Print ans
System.out.print(ans);
}
// Driver Code
public static void main(String[] args)
{
// Given N and M
int N = 2, M = 3;
// Function Call
noOfArraysPossible(N, M);
}
}
// This code is contributed by Princi Singh
Python3
# Python3 program for the above approach
# Function to find the number of arrays
# following the given condition
def noOfArraysPossible(N, M):
# Initialize answer
ans = 1
# Calculate nPm
for i in range(N):
ans = ans * (M - i)
# Print ans
print(ans)
# Driver Code
if __name__ == "__main__" :
# Given N and M
N = 2
M = 3
# Function Call
noOfArraysPossible(N, M)
# This code is contributed by jana_sayantan
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to find the number of arrays
// following the given condition
static void noOfArraysPossible(int N, int M)
{
// Initialize answer
int ans = 1;
// Calculate nPm
for (int i = 0; i < N; ++i)
{
ans = ans * (M - i);
}
// Print ans
Console.Write(ans);
}
// Driver Code
public static void Main()
{
// Given N and M
int N = 2, M = 3;
// Function Call
noOfArraysPossible(N, M);
}
}
// This code is contributed by susmitakundugoaldanga
Javascript
输出:
6
时间复杂度: O(N)
辅助空间: O(1)