Saturday, 9 April 2016

Ice Cream Parlor Hacker Rank Problem Solution.

Sunny and Johnny together have M dollars they want to spend on ice cream. The parlor offers N flavors, and they want to choose two flavors so that they end up spending the whole amount.
You are given the cost of these flavors. The cost of the ith flavor is denoted by ci. You have to display the indices of the two flavors whose sum is M.
Input Format
The first line of the input contains TT test cases follow. 
Each test case follows the format detailed below: The first line contains M. The second line contains N. The third line contains N space-separated integers denoting the price of each flavor. Here, the ith integer denotes ci.
Output Format
Output two integers, each of which is a valid index of a flavor. The lower index must be printed first. Indices are indexed from 1 to N.
Constraints
1T50 
2M10000 
2N10000 
1ci 10000,where i[1,N] 
The prices of any two items may be the same and each test case has a unique solution.
Sample Input
2
4
5
1 4 5 3 2
4
4
2 2 4 3
Sample Output
1 4
1 2
Explanation
The sample input has two test cases. 
For the 1st, the amount M = 4 and there are 5 flavors at the store. The flavors indexed at 1 and 4 sum up to 4. 
For the 2nd test case, the amount M = 4 and the flavors indexed at 1 and 2 sum up to 4.

Solution:

#include <bits/stdc++.h>
using namespace std;
/*
    *
    * Prosen Ghosh
    * American International University - Bangladesh (AIUB)
    *
*/
void call(vector<int>ar,int N,int M){
    for(int i = 0; i < N; i++){
        for(int j = i+1; j < N; j++){
            if(ar[i] + ar[j] == M){
                cout << i+1 << " " << j+1 << endl;
                return;
            }
        }
    }
}
int main() {
    int T,M,N,a;
    cin >> T;
    for(int t = 1; t <= T; t++){
        cin >> M >> N;
        vector<int>ar;
        for(int i = 0; i < N; i++){
            cin >> a;
            ar.push_back(a);
        }
        call(ar,N,M);
    }
    return 0;
}

No comments:

Post a Comment