📜  查找大小为N的数组,该数组恰好有K个子数组,且总和为S

📅  最后修改于: 2021-04-24 19:37:04             🧑  作者: Mango

给定三个整数N,K和S ,任务是选择一个大小为N的数组,以便精确地存在总数为S的K个子数组。

注意:可以有很多解决方案阵列来解决此问题。

例子:

方法:
用于此问题的解决方案数组之一包含S个元素K次和S + 1个元素(NK)次,以形成一个恰好一个元素的K个子数组,其中S为和。如果我们组合数组中的任何两个或更多个元素,则其总和将大于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


输出:
3 3 4 4