📌  相关文章
📜  L到R范围内的值组成的长度为N的非递减数组的计数

📅  最后修改于: 2021-04-22 09:25:41             🧑  作者: Mango

给定整数NLR ,任务是计算允许重复的,长度为N的非递减数组的数量,该数组的范围为[L,R]。

例子:

方法:

  • 由于已知数组中的最小数为L而最大数为R。
  • 如果剩余的(N – 2)个索引用L填充,则获得最小的可能总和;如果剩余的(N-2)个索引用R填充,则获得最大的可能总和
  • 可以得出结论,存在一个数字组合,其结果之和介于最小可能和最大可能和之间。
  • 因此,可以通过以下方式计算总和的总数:
    [(N – 2)* R –(N – 2)* L] + 1 =(N – 2)*(R – L)+ 1

下面是上述方法的实现:

C++
// C++ implementation of the approach
  
#include 
using namespace std;
  
// Function to return the count
// of different arrays
int countSum(int N, int L, int R)
{
  
    // No such combination exists
    if (L > R) {
        return 0;
    }
  
    // Arrays formed with single elements
    if (N == 1) {
        return R - L + 1;
    }
  
    if (N > 1) {
        return (N - 2) * (R - L) + 1;
    }
}
  
// Driver code
int main()
{
    int N = 4, L = 4, R = 6;
  
    cout << countSum(N, L, R);
  
    return 0;
}


Java
// Java implementation of the approach
class GFG
{
  
// Function to return the count
// of different arrays
static int countSum(int N, int L, int R)
{
  
    // No such combination exists
    if (L > R)
    {
        return 0;
    }
  
    // Arrays formed with single elements
    if (N == 1)
    {
        return R - L + 1;
    }
  
    if (N > 1)
    {
        return (N - 2) * (R - L) + 1;
    }
    return 0;
}
  
// Driver code
public static void main(String[] args)
{
    int N = 4, L = 4, R = 6;
  
    System.out.print(countSum(N, L, R));
}
}
  
// This code is contributed by 29AjayKumar


Python3
# Python3 implementation of the approach
  
# Function to return the count
# of different arrays
def countSum(N, L, R):
  
    # No such combination exists
    if (L > R):
        return 0;
  
    # Arrays formed with single elements
    if (N == 1):
        return R - L + 1;
    if (N > 1):
        return (N - 2) * (R - L) + 1;
      
    return 0;
  
# Driver code
if __name__ == '__main__':
    N, L, R = 4, 4, 6;
  
    print(countSum(N, L, R));
  
# This code is contributed by 29AjayKumar


C#
// C# implementation of the approach
using System;
  
class GFG
{
  
// Function to return the count
// of different arrays
static int countSum(int N, int L, int R)
{
  
    // No such combination exists
    if (L > R)
    {
        return 0;
    }
  
    // Arrays formed with single elements
    if (N == 1)
    {
        return R - L + 1;
    }
  
    if (N > 1)
    {
        return (N - 2) * (R - L) + 1;
    }
    return 0;
}
  
// Driver code
public static void Main(String[] args)
{
    int N = 4, L = 4, R = 6;
  
    Console.Write(countSum(N, L, R));
}
}
  
// This code is contributed by PrinciRaj1992


输出:
5

时间复杂度: O(1)