HackerRank: B'day Gift
https://codepair.hackerrank.com/paper/dJhk9ttD?b=eyJyb2xlIjoiY2FuZGlkYXRlIiwibmFtZSI6ImplZmZlcnl5dWFuIiwiZW1haWwiOiJ5dWFueXVuLmtlbm55QGdtYWlsLmNvbSJ9
for(int i = 0; i < numS; i ++)
{
total += Integer.parseInt(in.readLine());
}
System.out.print(total/2);
if(total%2 != 0)
{
System.out.println(".5");
}
else
{
System.out.println(".0");
}
Isaac has to buy a new HackerPhone for his girlfriend Amy. He is exploring the shops in the town to compare the prices whereupon he finds a shop located on the first floor of a building, that has a unique pricing policy. There are N steps leading to the shop. A numbered ball is placed on each of the steps.
The shopkeeper gives Isaac a fair coin and asks him to toss the coin before climbing each step. If the result of the toss is a 'Heads', Isaac should pick up the ball, else leave it and proceed to the next step.
The shopkeeper gives Isaac a fair coin and asks him to toss the coin before climbing each step. If the result of the toss is a 'Heads', Isaac should pick up the ball, else leave it and proceed to the next step.
The shopkeeper then asks Isaac to find the sum of all the numbers he has picked up (let's say S). The price of the HackerPhone is then the expected value of S. Help Isaac find the price of the HackerPhone.
Short Answer
Calculate summation of numbers on all the balls and call it X. X/2 will be the answer.
Long Answer
Let us consider number written on a particular step and call it p. Probability the he will pick p is 1/2, and It is an independent event , So It will contribute X*1/2 to final expected sum. We will do it for all number written on each and every step. So, final output will be sum of all elements divided by 2.
In other way, Let us consider number written on a particular step and call it p. There will exactly 2^N-1 set which will contain p and there will be exactly same number of sets which will not contain p. So, number p will contribute p*(2^(N-1)) to total sum.
Number of subsets = 2^N
Sum of all element of all subsets = (sum of elements of every step) * 2^(N-1) // as we did for p
So expected sum = (sum of element written on each step) / 2
Number of subsets = 2^N
Sum of all element of all subsets = (sum of elements of every step) * 2^(N-1) // as we did for p
So expected sum = (sum of element written on each step) / 2
https://codepair.hackerrank.com/paper/dJhk9ttD?b=eyJyb2xlIjoiY2FuZGlkYXRlIiwibmFtZSI6ImplZmZlcnl5dWFuIiwiZW1haWwiOiJ5dWFueXVuLmtlbm55QGdtYWlsLmNvbSJ9
for(int i = 0; i < numS; i ++)
{
total += Integer.parseInt(in.readLine());
}
System.out.print(total/2);
if(total%2 != 0)
{
System.out.println(".5");
}
else
{
System.out.println(".0");
}