给定一个由整数arr []和两个整数X和Y组成的数组,任务是检查是否有可能获得一个具有和X的序列,以使得子序列的每个元素的总和乘以一个数组元素等于Y 。
注意:此处X始终小于Y。
例子:
Input: arr[] = {1, 2, 7, 9, 10}, X = 11, Y = 13
Output: Yes
Explanation:
The given value of X( = 11) can be split into a sequence {9, 2} such that 9 * 1(= arr[0] + 2 * 2(= arr[1]) = 13( = Y)
Input: arr[] ={1, 3, 5, 7}, X = 27, Y = 34
Output: No
方法:请按照以下步骤解决问题:
- 计算Y和X的差。
- 对于每个大于1的数组元素arr [i] ,更新(Y – X)%(arr [i] – 1) 。
- 如果差减小为0,则打印“是”。否则,打印“否” 。
下面是上述方法的实现:
C++
// C++ Program to implement
// the above approach
#include
using namespace std;
// Function to check if it is possible
// to obtain sum Y from a sequence of
// sum X from the array arr[]
void solve(int arr[], int n, int X, int Y)
{
// Store the difference
int diff = Y - X;
// Iterate over the array
for (int i = 0; i < n; i++) {
if (arr[i] != 1) {
diff = diff % (arr[i] - 1);
}
}
// If diff reduced to 0
if (diff == 0)
cout << "Yes";
else
cout << "No";
}
// Driver Code
int main()
{
int arr[] = { 1, 2, 7, 9, 10 };
int n = sizeof(arr) / sizeof(arr[0]);
int X = 11, Y = 13;
solve(arr, n, X, Y);
return 0;
}
Java
// Java program to implement
// the above approach
class GFG{
// Function to check if it is possible
// to obtain sum Y from a sequence of
// sum X from the array arr[]
static void solve(int arr[], int n,
int X, int Y)
{
// Store the difference
int diff = Y - X;
// Iterate over the array
for(int i = 0; i < n; i++)
{
if (arr[i] != 1)
{
diff = diff % (arr[i] - 1);
}
}
// If diff reduced to 0
if (diff == 0)
System.out.print( "Yes");
else
System.out.print("No");
}
// Driver Code
public static void main (String []args)
{
int arr[] = { 1, 2, 7, 9, 10 };
int n = arr.length;
int X = 11, Y = 13;
solve(arr, n, X, Y);
}
}
// This code is contributed by chitranayal
Python3
# Python3 program to implement
# the above approach
# Function to check if it is possible
# to obtain sum Y from a sequence of
# sum X from the array arr[]
def solve(arr, n, X, Y):
# Store the difference
diff = Y - X
# Iterate over the array
for i in range(n):
if(arr[i] != 1):
diff = diff % (arr[i] - 1)
# If diff reduced to 0
if(diff == 0):
print("Yes")
else:
print("No")
# Driver Code
arr = [ 1, 2, 7, 9, 10 ]
n = len(arr)
X, Y = 11, 13
# Function call
solve(arr, n, X, Y)
# This code is contributed by Shivam Singh
C#
// C# program to implement
// the above approach
using System;
class GFG{
// Function to check if it is possible
// to obtain sum Y from a sequence of
// sum X from the array []arr
static void solve(int []arr, int n,
int X, int Y)
{
// Store the difference
int diff = Y - X;
// Iterate over the array
for(int i = 0; i < n; i++)
{
if (arr[i] != 1)
{
diff = diff % (arr[i] - 1);
}
}
// If diff reduced to 0
if (diff == 0)
Console.Write("Yes");
else
Console.Write("No");
}
// Driver Code
public static void Main(String []args)
{
int []arr = { 1, 2, 7, 9, 10 };
int n = arr.Length;
int X = 11, Y = 13;
solve(arr, n, X, Y);
}
}
// This code is contributed by Amit Katiyar
输出:
Yes
时间复杂度: O(N)
辅助空间: O(1)