给定三个整数N、K 和 S ,任务是选择一个大小为N的数组,使得恰好存在K个总和为S 的子数组。
注意:这个问题可以有很多解数组。
例子:
Input: N = 4, K = 2, S = 3
Output: 1 2 3 4
Explanation:
One of the possible array is [ 1, 2, 3, 4 ]
There exist exactly two subarrays with sum 3
Subarrays with Sum(3) = [ [ 1, 2 ], [ 3 ] ]
Input: N = 5, K = 3, S = 50
Output: 25 25 25 10 40
Explanation:
One of the possible array is [ 25, 25, 25, 10, 40 ]
There exist exactly three subarrays with sum 50
Subarrays with Sum(50) = [ [ 25, 25 ], [ 25, 25 ], [ 10, 40 ] ]
方法:
该问题的解数组之一包含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