HackerRank Ice Cream Parlor Problem Solution
In this bpost, we will solve HackerRank Ice Cream Parlor Problem Solution.
Two friends like to pool their money and go to the ice cream parlor. They always choose two distinct flavors and they spend all of their money.
Given a list of prices for the flavors of ice cream, select the two that will cost all of the money they have.
Example
m = 6 cost = [1, 3, 4, 5, 6]
The two flavors that cost 1 and 5 meet the criteria. Using 1-based indexing, they are at indices 1 and 4.
Function Description
Complete the icecreamParlor function in the editor below.
icecreamParlor has the following parameter(s):
- int m: the amount of money they have to spend
- int cost[n]: the cost of each flavor of ice cream
Returns
- int[2]: the indices of the prices of the two flavors they buy, sorted ascending
Input Format
The first line contains an integer, t, the number of trips to the ice cream parlor. The next t sets of lines each describe a visit.
Each trip is described as follows:
- The integer m, the amount of money they have pooled.
- The integer n, the number of flavors offered at the time.
- n space-separated integers denoting the cost of each flavor: cost cost[1], cost[2],…, cost[n]].
Note: The index within the cost array represents the flavor of the ice cream purchased.
Sample Input
STDIN Function ----- -------- 2 t = 2 4 k = 4 5 cost[] size n = 5 1 4 5 3 2 cost = [1, 4, 5, 3, 2] 4 k = 4 4 cost[] size n = 4 2 2 4 3 cost=[2, 2,4, 3]
Sample Output
1 4
1 2
Explanation
Sunny and Johnny make the following two trips to the parlor:
- The first time, they pool together m = 4 dollars. Of the five flavors available that day, flavors 1 and 4 have a total cost of 1 + 3 = 4.
- The second time, they pool together m = 4 dollars. Of the four flavors available that day, flavors 1 and 2 have a total cost of 2 + 2 = 4.
Ice Cream Parlor C Solution
#include<stdio.h>
void find(int arr[],int size,int C){
int i,j;
i=0;j=i+1;
for(i=0;i<size;i++){
for(j=i+1;j<=size;j++){
if(arr[i]+arr[j]==C){
printf("%d %d",i+1,j+1);
return;
}
}
}
}
int main(){
int T,i;
scanf("%d",&T);
for(i=0;i<T;i++){
int C,L;
scanf("%d",&C);
scanf("%d",&L);
int arr[L],j,k,l;
for(l=0;l<L;l++)
scanf("%d",&arr[l]);
find(arr,L-1,C);
printf("\n");
}
return 0;
}
Ice Cream Parlor C++ Solution
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
typedef pair<int,int>ii;
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int T;
cin>>T;
while(T--){
int totMoneyAvail,n,amount;
cin>>totMoneyAvail>>n;
vector<ii>prices(n);
for(int i=0;i<n;i++){
cin>>amount;
prices[i] = ii(amount,i);
}
sort(prices.begin(),prices.end());
int lower = 0,upper = n-1;
while(lower < upper){
int sum = prices[lower].first + prices[upper].first;
if(sum == totMoneyAvail){
cout<<min(prices[lower].second,prices[upper].second)+1<<" "<<max(prices[lower].second,prices[upper].second)+1<<"\n";
break;
}
else if(sum > totMoneyAvail)upper--;
else lower++;
}
}
return 0;
}
Ice Cream Parlor C Sharp Solution
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IceCreamParlor
{
class Program
{
static void Main(string[] args)
{
int t = Convert.ToInt32(Console.ReadLine());
for (int i = 0; i < t; i++)
{
int c = Convert.ToInt32(Console.ReadLine());
int l = Convert.ToInt32(Console.ReadLine());
Dictionary<int, int> dict = new Dictionary<int, int>();
int[] list = Console.ReadLine().Split().Select((string x) => Convert.ToInt32(x)).ToArray();
for (int j = 0; j < list.Length; j++)
{
if (dict.ContainsKey(c - list[j]))
{
Console.WriteLine("{0} {1}", dict[c - list[j]] + 1, j + 1);
break;
}
dict[list[j]] = j;
}
}
}
}
}
Ice Cream Parlor Java Solution
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
class Result {
/*
* Complete the 'icecreamParlor' function below.
*
* The function is expected to return an INTEGER_ARRAY.
* The function accepts following parameters:
* 1. INTEGER m
* 2. INTEGER_ARRAY arr
*/
public static List<Integer> icecreamParlor(int k, List<Integer> arr) {
// Write your code here
ArrayList<Integer> l=new ArrayList<>();
Map<Integer,Integer> m=new HashMap<>();
int o=1;
for(Integer p: arr){
if(m.containsKey(k-p)){
l.add(m.get(k-p));
l.add(o);
break;
}
m.put(p,o++);
}
System.out.println(m);
m.clear();
return l;
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(System.getenv("OUTPUT_PATH")));
int t = Integer.parseInt(bufferedReader.readLine().trim());
IntStream.range(0, t).forEach(tItr -> {
try {
int m = Integer.parseInt(bufferedReader.readLine().trim());
int n = Integer.parseInt(bufferedReader.readLine().trim());
List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
List<Integer> result = Result.icecreamParlor(m, arr);
bufferedWriter.write(
result.stream()
.map(Object::toString)
.collect(joining(" "))
+ "\n"
);
} catch (IOException ex) {
throw new RuntimeException(ex);
}
});
bufferedReader.close();
bufferedWriter.close();
}
}
Ice Cream Parlor JavaScript Solution
function buyIceCream(ar){
var m = parseInt(ar.shift(), 10),
n = parseInt(ar.shift(), 10),
c = ar[0].split(' '),
i = 0, j, price;
for (; i < n; i++) {
price = parseInt(c[i]);
j = i + 1;
for(; j < n; j++) {
if (price + parseInt(c[j],10) === m){
return ''+(i + 1)+' '+(j + 1);
}
}
}
}
function processData(input) {
var lines = input.split('\n'),
t = parseInt(lines.shift(),10),
i = 0;
for (; i < t; i++) {
process.stdout.write(''+buyIceCream(lines.splice(0,3))+'\n');
}
}
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
_input += input;
});
process.stdin.on("end", function () {
processData(_input);
});
Ice Cream Parlor Python Solution
import sys
def main():
t = int(sys.stdin.readline())
for _ in range(t):
m = int(sys.stdin.readline())
n = int(sys.stdin.readline())
prices = [int(i) for i in sys.stdin.readline().split()]
for i in range(n):
for j in range(i, n):
if prices[i] + prices[j] == m and i != j:
print(i + 1, j + 1)
if __name__ == "__main__":
main()