给定三个整数N 、 K和X ,任务是创建一个长度为N的数组,其所有 K 长度子数组的模N 之和为X 。
例子:
Input: N = 6, K = 3, X = 3
Output: 9 6 6 9 6 6
Explanation:
All subarrays of length 3 and their respective sum%N values are as follows:
[9, 6, 6] Sum = 21 % 6 = 3
[6, 6, 9] sum = 21 % 6 = 3
[6, 9, 6] sum = 21 % 6 = 3
[9, 6, 6] sum = 21 % 6 = 3
Since all its subarrays have sum % N = X (=3), the generated array is valid.
Input: N = 4, K = 2, X = 2
Output: 6 4 6 4
方法:
我们可以观察到,为了使任何大小为K模N 的子数组的总和等于X ,该子数组需要有K – 1 个元素等于N和 1 个元素等于N + X 。
插图:
If N = 6, K = 3, X = 3
Here a K length subarray needs to be a permutation of {9, 6, 6} where 2 (K – 1) elements are divisible by 6 and 1 element has modulo N equal to X( 9%6 = 3)
Sum of subarray % N = (21 % 6) = 3 (same as X)
Hence, each K length
因此,请按照以下步骤解决问题:
- 从0到N – 1迭代i ,以打印所需子数组的第i个元素。
- 如果i % K等于0 ,则打印N + X 。否则,对于i 的所有其他值,打印N 。
- 这确保了每个可能的 K 长度子数组都有一个总和K*N + X 。因此,对于所有这样的子阵列,求和模N是X。
下面是上述方法的实现。
C++
// C++ implementation of the
// above approach
#include
using namespace std;
// Funtion prints the required array
void createArray(int n, int k, int x)
{
for (int i = 0; i < n; i++) {
// First element of each K
// length subarrays
if (i % k == 0) {
cout << x + n << " ";
}
else {
cout << n << " ";
}
}
}
// Driver Program
int main()
{
int N = 6, K = 3, X = 3;
createArray(N, K, X);
}
Java
// Java implementation of the above approach
import java.util.*;
class GFG{
// Function prints the required array
static void createArray(int n, int k, int x)
{
for(int i = 0; i < n; i++)
{
// First element of each K
// length subarrays
if (i % k == 0)
{
System.out.print((x + n) + " ");
}
else
{
System.out.print(n + " ");
}
}
}
// Driver Code
public static void main(String args[])
{
int N = 6, K = 3, X = 3;
createArray(N, K, X);
}
}
// This code is contributed by Code_Mech
Python3
# Python3 implementation of the
# above approach
# Funtion prints the required array
def createArray(n, k, x):
for i in range(n):
# First element of each K
# length subarrays
if (i % k == 0):
print(x + n, end = " ")
else :
print(n, end = " ")
# Driver code
N = 6
K = 3
X = 3
createArray(N, K, X)
# This code is contributed by Vishal Maurya.
C#
// C# implementation of the above approach
using System;
class GFG{
// Function prints the required array
static void createArray(int n, int k, int x)
{
for(int i = 0; i < n; i++)
{
// First element of each K
// length subarrays
if (i % k == 0)
{
Console.Write((x + n) + " ");
}
else
{
Console.Write(n + " ");
}
}
}
// Driver Code
public static void Main()
{
int N = 6, K = 3, X = 3;
createArray(N, K, X);
}
}
// This code is contributed by Code_Mech
Javascript
9 6 6 9 6 6
时间复杂度: O(N)
辅助空间: O(1)
如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live