Problem
: Sheldon Cooper and his beverage paradigm
Sheldon Cooper, Leonard Hofstadter and Penny decide
to go for drinks at Cheese cake factory. Sheldon proposes to make a game out of
this. Sheldon proposes as follows,
- To
decide the amount of beverage they plan to consume, say X.
- Then
order for a random number of different drinks, say {A, B, C, D, E, F} of
quantities {a, b, c, d, e, f} respectively.
- If
quantity of any three drinks add up to X then we'll have it else we'll
return the order.
E.g. If a + d + f = X then True else False
You are given
1.
Number
of bottles N corresponding to different beverages and hence their sizes
2.
Next
N lines, contain a positive integer corresponding to the size of the beverage
3.
Last
line consists of an integer value, denoted by X above
Your task is to
help find out if there can be any combination of three beverage sizes that can
sum up to the quantity they intend to consume. If such a combination is
possible print True else False
Input
Format:
1.
First
line contains number of bottles ordered denoted by N
2.
Next
N lines, contains a positive integer Ai, the size of the ith bottle
3.
Last
line contains the quantity they intend to consume denoted by X in text above
Output
Format:
True, if combination is possible
False, if combination is not possible
True, if combination is possible
False, if combination is not possible
Constraints:
N
>= 3
Ai >
0
1
<= i <= N
X
> 0
Sample
Input and Output
SNo.
|
Input
|
Output
|
1
|
6 1 4 45 6 10 8 22 |
True |
2
|
4 1 3 12 4 14 |
False |
Solution in Java:
import java.util.Scanner;
import java.util.Stack;
public class Shell
{
private Stack<Integer> stack = new Stack<Integer>();
private int sumin = 0,sizeStack=0;
int c=0;
public void populateSubset(int[] data, int fromIndex, int last,int t)
{
int TARGET_SUM=t;
if (sumin == TARGET_SUM)
{
if(sizeStack==3)
{
count(stack);
}
}
for (int now = fromIndex; now < last; now++) {
if (sumin + data[now] <= TARGET_SUM) {
stack.push(data[now]);
sumin += data[now];
sizeStack=stack.size();
populateSubset(data, now + 1, last,TARGET_SUM);
sumin -= (Integer) stack.pop();
}
}
}
private void count(Stack<Integer> stack)
{
c++;
}
void print()
{
if(c>0)
System.out.println("True");
else
System.out.println("False");
}
public static void main(String [] args)
{
Shell get = new Shell();
int t1,n1,i;
Scanner sc=new Scanner(System.in);
n1=sc.nextInt();
int []ip=new int[n1];
for(i=0;i<n1;i++)
{
ip[i]=sc.nextInt();
}
t1=sc.nextInt();
get.populateSubset(ip, 0, ip.length,t1);
get.print();
}
}
No comments:
Post a Comment