Find an array of size N having exactly K subarrays with sum S
Last Updated :
11 Jul, 2022
Given three integers N, K and S, the task is to choose an array of size N such that there exists exactly K sub-arrays with sum S.
Note: There can be many solution arrays to this problem.
Examples:
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 ] ]
Approach:
One of the Solution Array for this problem contains S element K times and S+1 element (N-K) times, to form K Sub-arrays of exactly one element with S as sum. If we combine any two or more elements of the array then it will give sum greater than S.
Below is the implementation of the above approach:
C++
#include<bits/stdc++.h>
using namespace std;
void SubarraysWithSumS( int n, int k, int s)
{
for ( int i=0;i<k;i++)
cout << s << " " ;
for ( int i=k;i<n;i++)
cout << s+1 << " " ;
}
int main()
{
int n = 4, k = 2, s = 3;
SubarraysWithSumS(n, k, s);
return 0;
}
|
Java
class GFG
{
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 + " " );
}
public static void main(String[] args)
{
int n = 4 , k = 2 , s = 3 ;
SubarraysWithSumS(n, k, s);
}
}
|
Python3
def SubarraysWithSumS(n, k, s):
for i in range (k):
print (s, end = " " )
for i in range (k, n):
print (s + 1 , end = " " )
n = 4
k = 2
s = 3
SubarraysWithSumS(n, k, s)
|
C#
using System;
class GFG
{
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 + " " );
}
public static void Main(String[] args)
{
int n = 4, k = 2, s = 3;
SubarraysWithSumS(n, k, s);
}
}
|
Javascript
<script>
function SubarraysWithSumS(n,k,s)
{
for (let i = 0; i < k; i++)
document.write(s + " " );
for (let i = k; i < n; i++)
document.write(s + 1 + " " );
}
let n = 4, k = 2, s = 3;
SubarraysWithSumS(n, k, s);
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(1)
Related Topic: Subarrays, Subsequences, and Subsets in Array
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...