Two friends Anna and Brian, are deciding how to split the bill at 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.
Example:
Input: n=4,k=1,bill={3,10,2,9}
Output: 5
Approach
Java
import java.util.Arrays;import java.util.List;import java.util.stream.Collectors;public class BillDivision {public static void main(String[] args) {int k = 1;int[] bill = { 3, 10, 2, 9 };int b = 12;List<Integer> l = Arrays.stream(bill).boxed().collect(Collectors.toList());bonAppetit(l, k, b);}static void bonAppetit(List<Integer> bill, int k, int b) {int n = bill.size();int i, sum = 0, b_charged, b_actual;for (i = 0; i < n; i++)sum = sum + bill.get(i);b_charged = b;b_actual = (sum - bill.get(k)) / 2;if (b_charged == b_actual) {System.out.println("Bon Appetit");} else {System.out.println(b_charged - b_actual);}}}
C++
#include <bits/stdc++.h>using namespace std;void bonAppetit(vector<int> bill, int k, int b){int n = bill.size();int i, sum = 0, b_charged, b_actual;for (i = 0; i < n; i++)sum = sum + bill[i];b_charged = b;b_actual = (sum - bill[k]) / 2;if (b_charged == b_actual){cout << "Bon Appetit\n";}else{cout << b_charged - b_actual;}}int main(){int n = 4, k = 1;vector<int> bill = {3, 10, 2, 9};int b = 12;bonAppetit(bill, k, b);return 0;}
No comments:
Post a Comment