Check if sum Y can be obtained from the Array by the given operations
Last Updated :
30 Apr, 2021
Given an array of integers arr[] and two integers X and Y, the task is to check if it is possible to obtain a sequence having sum X such that the sum of each element of the subsequence multiplied by an array element is equal to Y.
Note: Here X is always less than Y.
Examples:
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
Approach: Follow the steps below in order to solve the problem:
- Calculate the difference between Y and X.
- For every array element arr[i], which is > 1, update (Y – X) % (arr[i] – 1).
- If the difference is reduced 0, print “Yes“. Otherwise, print “No”.
Below is the implementation of the above approach:
C++
#include <iostream>
using namespace std;
void solve( int arr[], int n, int X, int Y)
{
int diff = Y - X;
for ( int i = 0; i < n; i++) {
if (arr[i] != 1) {
diff = diff % (arr[i] - 1);
}
}
if (diff == 0)
cout << "Yes" ;
else
cout << "No" ;
}
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
class GFG{
static void solve( int arr[], int n,
int X, int Y)
{
int diff = Y - X;
for ( int i = 0 ; i < n; i++)
{
if (arr[i] != 1 )
{
diff = diff % (arr[i] - 1 );
}
}
if (diff == 0 )
System.out.print( "Yes" );
else
System.out.print( "No" );
}
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);
}
}
|
Python3
def solve(arr, n, X, Y):
diff = Y - X
for i in range (n):
if (arr[i] ! = 1 ):
diff = diff % (arr[i] - 1 )
if (diff = = 0 ):
print ( "Yes" )
else :
print ( "No" )
arr = [ 1 , 2 , 7 , 9 , 10 ]
n = len (arr)
X, Y = 11 , 13
solve(arr, n, X, Y)
|
C#
using System;
class GFG{
static void solve( int []arr, int n,
int X, int Y)
{
int diff = Y - X;
for ( int i = 0; i < n; i++)
{
if (arr[i] != 1)
{
diff = diff % (arr[i] - 1);
}
}
if (diff == 0)
Console.Write( "Yes" );
else
Console.Write( "No" );
}
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);
}
}
|
Javascript
<script>
function solve(arr, n, X, Y)
{
var diff = Y - X;
for ( var i = 0; i < n; i++)
{
if (arr[i] != 1)
{
diff = diff % (arr[i] - 1);
}
}
if (diff == 0)
document.write( "Yes" );
else
document.write( "No" );
}
var arr = [ 1, 2, 7, 9, 10 ];
var n = arr.length;
var X = 11, Y = 13;
solve(arr, n, X, Y);
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...