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 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.
Example:
Input: balls_count = 3, balls = {1, 1, 2}
Output: 2.0
Approach
Java
public class BdayGift {public static void main(String[] args) {int balls_count = 3;int balls[] = { 1, 1, 2 };System.out.println(solve(balls));}static double solve(int[] balls) {double sum = 0;for (int i : balls) {sum += i;}return (sum / 2);}}
C++
#include <bits/stdc++.h>using namespace std;double solve(vector<int> balls){double sum = 0;for (auto i : balls){sum += i;}return (sum / 2);}int main(){int balls_count = 3;vector<int> balls = {1, 1, 2};double result = solve(balls);cout << fixed << setprecision(1) << result << "\n";return 0;}
No comments:
Post a Comment