Ice Cream Parlor

Sunny and Johnny like to pool their money and go to the ice cream parlor. Johnny never buys the same flavor that Sunny does. The only other rule they have is that 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:

Input: m=4, n=5, arr[]={1,4,5,3,2}
Output: 1 4

Approach

Java


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class IceCreamParlor {
    public static void main(String[] args) {

        int m = 4;

        int[] arr = { 14532 };

        int[] result = icecreamParlor(m, arr);
        System.out.println(Arrays.toString(result));

    }

    private static int[] icecreamParlor(int mint[] arr) {
        int n = arr.length;
        List<Integerres = new ArrayList<Integer>();

        int ij;
        for (i = 0; i < n - 1; i++)
            for (j = i + 1; j < n; j++)
                if (arr[i] + arr[j] == m) {
                    res.add(i + 1);
                    res.add(j + 1);
                    break;
                }
        return res.stream().mapToInt(Integer::intValue).toArray();
    }
}

C++

#include <bits/stdc++.h>
using namespace std;

vector<inticecreamParlor(int mvector<intarr)
{
    int n = arr.size();
    vector<intres;
    int ij;
    for (i = 0i < n - 1i++)
        for (j = i + 1j < nj++)
            if (arr[i] + arr[j] == m)
            {
                res.push_back(i + 1);
                res.push_back(j + 1);
                break;
            }
    return res;
}

int main()
{

    int m = 4;

    int n = 5;

    vector<intarr = {14532};

    vector<intresult = icecreamParlor(marr);

    for (int i = 0i < result.size(); i++)
    {
        cout << result[i];

        if (i != result.size() - 1)
        {
            cout << " ";
        }
    }

    cout << "\n";

    return 0;
}


No comments:

Post a Comment