HackerRank Bill Division Solution

Hello Programmers, In this post, you will learn how to solve HackerRank Bill Division Solution. This problem is a part of the HackerRank Algorithms Series.

One more thing to add, don’t straight away look for the solutions, first try to solve the problems by yourself. If you find any difficulty after trying several times, then look for the solutions. We are going to solve the HackerRank Algorithms problems using C, CPP, JAVA, PYTHON, JavaScript & SCALA Programming Languages.

You can practice and submit all HackerRank problem solutions in one place. Find a solution for other domains and Sub-domain. I.e. Hacker Rank solution for HackerRank C ProgrammingHackerRank C++ ProgrammingHackerRank Java Programming, HackerRank Python ProgrammingHackerRank Linux ShellHackerRank SQL Programming, and HackerRank 10 days of Javascript.

HackerRank Bill Division Solution
HackerRank Bill Division Solution

As you already know that this site does not contain only the Hacker Rank solutions here, you can also find the solution for other problems. I.e. Web Technology, Data StructuresRDBMS ProgramsJava Programs Solutions,  Fiverr Skills Test answersGoogle Course AnswersLinkedin Assessment, and Coursera Quiz Answers.

HackerRank Bill Division

Task

Two friends Anna and Brian, are deciding how to split the bill at a dinner. Each will only pay for the items they consume. Brian gets the check and calculates Anna’s portion. You must determine if his calculation is correct.

For example, assume the bill has the following prices: bill = [2, 4, 6]. Anna declines to eat item k = bill[2] which costs 6. If Brian calculates the bill correctly, Anna will pay (2 + 4)/2 = 3. If he includes the cost of bill[2], he will calculate (2 + 4 + 6)/2 = 6. In the second case, he should refund 3 to Anna.

Function Description

Complete the bonAppetit function in the editor below. It should print Bon Appetit if the bill is fairly split. Otherwise, it should print the integer amount of money that Brian owes Anna.

bonAppetit has the following parameter(s):

  • bill: an array of integers representing the cost of each item ordered
  • k: an integer representing the zero-based index of the item Anna doesn’t eat
  • b: the amount of money that Anna contributed to the bill

Input Format

The first line contains two space-separated integers n and k, the number of items ordered and the 0-based index of the item that Anna did not eat.
The second line contains n space-separated integers bill[i] where 0 <= i < n.
The third line contains an integer, b, the amount of money that Brian charged Anna for her share of the bill.

Constraints

  • 2 <= n <= 105
  • 0 <= k < n
  • 0 <= bill[i] <= 104
  • 0 <= b <= bill[i]
  • The amount of money due Anna will always be an integer

Output Format

If Brian did not overcharge Anna, print Bon Appetit on a new line; otherwise, print the difference (i.e., bcharged – bactual) that Brian must refund to Anna. This will always be an integer.

Sample Input 0

4 1
3 10 2 9
12

Sample Output 0

5

Explanation 0

Anna didn’t eat item bill[1] = 10, but she shared the rest of the items with Brian. The total cost of the shared items is 3 + 2 + 9 = 14 and, split in half, the cost per person is bactual = 7. Brian charged her bcharged = 12 for her portion of the bill. We print the amount Anna was overcharged, bcharged – bactual = 12 – 7 = 5, on a new line.

Sample Input 1

4 1
3 10 2 9
7

Sample Output 1

Bon Appetit

Explanation 1

Anna didn’t eat item bill[1] = 10, but she shared the rest of the items with Brian. The total cost of the shared items is 3 + 2 + 9 = 14 and, split in half, the cost per person is bactual = 7. Because bactual = bcharged = 7, we print Bon Appetit on a new line.

HackerRank Bill Division Solution

Bill Division Solution in C

#include<stdio.h>
int main()
{
    int n,k;
    scanf("%d %d",&n,&k);
    int i,a[n];
    for(i=0;i<n;i++)
        scanf("%d",&a[i]);
    int sum = 0;
    for(i=0;i<n;i++)
        sum += a[i];
    int paid;
    scanf("%d",&paid);
    int toBePaid = sum-a[k];
    if((toBePaid)/2==paid)
        printf("Bon Appetit\n");
    else
        printf("%d\n",paid-(toBePaid)/2);
    return 0;
}

Bill Division Solution in Cpp

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;


int main() {
    int n, k, sum=0;
    cin >> n >> k;
    for (int i=0;i<n;i++) {
        int a;
        cin >> a;
        if (i!=k) sum+=a;
    }
    int l;
    cin >> l;
    if (sum/2==l) cout << "Bon Appetit" << endl;
    else cout << l-sum/2 << endl;
}

Bill Division Solution in Java

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        int k=sc.nextInt();
        int a[]=new int[n];
        int sum=0;
        for(int i=0;i<n;i++){
            a[i]=sc.nextInt();
            if(i!=k){
                sum+=a[i];
            }
        }
        int num=sc.nextInt();
        if(num==sum/2)
            System.out.println("Bon Appetit");
        else
            System.out.println(num-sum/2);
    }
}

Bill Division Solution in Python

n, k = map(int, raw_input().split(' '))
c = map(int, raw_input().split(' '))

t = (sum(c) - c[k]) / 2
z = int(raw_input())
if (t == z):
    print "Bon Appetit"
else:
    print abs(t - z)

Bill Division Solution using JavaScript

function processData(input) {
    var next = 0;
    var Ns = input[next++].split(' ');
    var N = parseInt(Ns[0]);
    var k = parseInt(Ns[1]);
    var sum = 0;
    var items = input[next++].split(' ').map(Number);
    var charged = input[next++];
    for (i = 0; i < items.length; i++) {
        if (i != k) {
            sum += items[i];
        }
    }
    if ((sum / 2) == charged) {
        console.log('Bon Appetit');
    } else {
        console.log(charged - (sum / 2));
    }
    
} 

process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});

process.stdin.on("end", function () {
   processData(_input.split('\n'));
});

Bill Division Solution in Scala

import scala.io._

object Solution {

    def main(args: Array[String]) {
        /* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution
*/      val nk = io.StdIn.readLine.split(" ").map(_.toInt)
        val n = nk(0)
        val k = nk(1)
        
        val nums = io.StdIn.readLine.split(" ").map(_.toInt)
        val actual = io.StdIn.readInt
        val ideal = (nums.sum - nums(k))/2
        if (actual - ideal == 0) {
            println("Bon Appetit")
        }
        else {
            println(actual - ideal)
        }
        
    
    }
}

Bill Division Solution in Pascal

{$mode objfpc}
program A;
var
  n, k: Integer;
  i: Integer;
  TotalCharge, AnnaShare, Charge: uInt64;
  c: Int64; 
begin
  ReadLn(n, k);
  for i := 0 to N - 1 do
  begin
    Read(c);
    TotalCharge := TotalCharge + 2 * c;
    if i <> k  then
      AnnaShare := AnnaShare + c;
  end;
  ReadLn(Charge);
  if 2 * Charge = AnnaShare then
    WriteLn('Bon Appetit')
  else
    WriteLn(Charge - AnnaShare div 2);
end.

Disclaimer: This problem (Bill Division) is generated by HackerRank but the solution is provided by Chase2learn. This tutorial is only for Educational and Learning purposes.

FAQ:

1. How do you solve the first question in HackerRank?

If you want to solve the first question of Hackerrank then you have to decide which programing language you want to practice i.e C programming, Cpp Programing, or Java programming then you have to start with the first program HELLO WORLD.

2. How do I find my HackerRank ID?

You will receive an email from HackerRank to confirm your access to the ID. Once you have confirmed your email, the entry will show up as verified on the settings page. You will also have an option to “Make primary”. Click on that option. Read more

3. Does HackerRank detect cheating?

yes, HackerRank uses a powerful tool to detect plagiarism in the candidates’ submitted code. The Test report of a candidate highlights any plagiarized portions in the submitted code and helps evaluators to verify the integrity of answers provided in the Test.

4. Does HackerRank use camera?

No for coding practice Hackerrank does not use camera but for companies’ interviews code submission time Hackerrank uses the camera.

5. Should I put HackerRank certificate on resume?

These certificates are useless, and you should not put them on your resume. The experience you gained from getting them is not useless. Use it to build a portfolio, and link to it on your resume. 

6. Can I retake HackerRank test?

The company which sent you the HackerRank Test invite owns your Test submissions and results. It’s their discretion to permit a reattempt for a particular Test. If you wish to retake the test, we recommend that you contact the concerned recruiter who invited you to the Test and request a re-invite. 

7. What is HackerRank?

HackerRank is a tech company that focuses on competitive programming challenges for both consumers and businesses. Developers compete by writing programs according to provided specifications. Wikipedi


Finally, we are now, in the end, I just want to conclude some important message for you

Note:- I compile all programs, if there is any case program is not working and showing an error please let me know in the comment section. If you are using adblocker, please disable adblocker because some functions of the site may not work correctly.

Please share our posts on social media platforms and also suggest to your friends to Join Our Groups. Don’t forget to subscribe. 

Sharing Is Caring

Leave a Comment