Hash Tables: Ice Cream Parlor

  • + 0 comments

    C++ Solution

    void whatFlavors(vector<int> cost, int money) 
    {
        map<int, int> hash;
        for(int i = 0; i < cost.size(); i++)
        {
            int remaining_money = money - cost[i];
            if(remaining_money <= 0) continue; // cant buy a second flavor so continues
            if(hash[remaining_money] > 0) //if it exists
            {
                cout << hash[remaining_money] << " " << i + 1 << endl;
                return;
            }
            hash[cost[i]] = i + 1;
        }
    }