📌  相关文章
📜  计算由前 M 个自然数组成的 N 个长度的数组,其子数组可以通过替换其少于一半的元素而成为回文

📅  最后修改于: 2021-09-07 02:18:10             🧑  作者: Mango

给定两个整数NM ,任务是找到具有范围[1, M]中元素的大小为N的数组的计数,其中所有长度大于1 的子数组都可以通过替换其少于一半的元素来回文即, floor(length/2)

例子:

方法:该问题可以基于以下观察来解决:

  • 使数组成为回文所需的最大允许操作次数可能是floor(size(array)/2)
  • 可以观察到,通过选择一个子数组,以相同的值开始和结束,使其成为回文所需的操作次数将小于floor(size of subarray)/2
  • 因此,任务简化为使用[1, M]范围内的整数值查找大小为N的数组的数量,其中不包含任何重复元素,这可以通过查找MN的排列来轻松完成,即Mp N ,等于M * (M – 1) * (M – 2) * … * (M – N + 1)。

请按照以下步骤解决问题:

  1. 初始化一个整数变量,比如ans = 1
  2. i = 0遍历到 N – 1并将ans更新为ans = ans * (Mi)
  3. 打印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