📌  相关文章
📜  找到一个大小为 N 的数组,其中恰好有 K 个子数组,总和为 S

📅  最后修改于: 2021-09-04 08:20:58             🧑  作者: Mango

给定三个整数N、K 和 S ,任务是选择一个大小为N的数组,使得恰好存在K个总和为S 的子数组。
注意:这个问题可以有很多解数组。
例子:

方法:
该问题的解数组之一包含S个元素K次和S+1个元素(NK)次,以S为和形成恰好一个元素的K个子数组。如果我们组合数组的任何两个或多个元素,那么它的总和将大于 S。
下面是上述方法的实现:

C++
// C++ program to find array
// with K subarrays with sum S
 
#include
using namespace std;
   
// Function to find array
// with K subarrays with sum S
void SubarraysWithSumS(int n, int k, int s)
{
    for(int i=0;i


Java
// Java program to find array
// with K subarrays with sum S
class GFG
{
     
// Function to find array
// with K subarrays with sum S
static void SubarraysWithSumS(int n, int k, int s)
{
    for(int i = 0; i < k; i++)
        System.out.print(s + " ");
    for(int i = k; i < n; i++)
        System.out.print(s + 1 + " ");
}
     
// Driver Code
public static void main(String[] args)
{
    int n = 4, k = 2, s = 3;
     
    // Function call
    SubarraysWithSumS(n, k, s);
}
}
 
// This code is contributed by 29AjayKumar


Python3
# Python3 program to find array
# with K subarrays with sum S
 
# Function to find array
# with K subarrays with sum S
def SubarraysWithSumS(n, k, s):
    for i in range(k):
        print(s, end=" ")
    for i in range(k, n):
        print(s + 1, end = " ")
 
# Driver Code
n = 4
k = 2
s = 3
 
# Function call
SubarraysWithSumS(n, k, s)
 
# This code is contributed by mohit kumar 29


C#
// C# program to find array
// with K subarrays with sum S
using System;
 
class GFG
{
     
// Function to find array
// with K subarrays with sum S
static void SubarraysWithSumS(int n, int k, int s)
{
    for(int i = 0; i < k; i++)
        Console.Write(s + " ");
    for(int i = k; i < n; i++)
        Console.Write(s + 1 + " ");
}
     
// Driver Code
public static void Main(String[] args)
{
    int n = 4, k = 2, s = 3;
     
    // Function call
    SubarraysWithSumS(n, k, s);
}
}
 
// This code is contributed by PrinciRaj1992


Javascript


输出:
3 3 4 4

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live