给定两个整数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(size of 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)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live