Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save shanecandoit/6c3009fa374e15aba9d330a08db16f53 to your computer and use it in GitHub Desktop.
Save shanecandoit/6c3009fa374e15aba9d330a08db16f53 to your computer and use it in GitHub Desktop.
icecream-parlor: Given a list of prices for the flavors of ice cream, select the two that will cost all of the money they have.
import java.util.*;
class Scratch {
public static void main(String[] args) {
// https://www.hackerrank.com/challenges/icecream-parlor/problem
// solved!
// Given a list of prices for the flavors of ice cream,
// select the two that will cost all of the money they have.
int m;
List<Integer> costs;
List<Integer> r;
m = 6;
costs = Arrays.asList(1,3,4,5,6);
r = icecreamParlor(m, costs);
// The two flavors that cost 1 and 5 meet the criteria.
// Using 1-based indexing, they are at indices 1 and 4.
System.out.println("r = " + r);
}
public static List<Integer> icecreamParlor(int m, List<Integer> arr) {
List<Integer> results = new ArrayList();
// O(n)
Map<Integer, Integer> numsIndex = new HashMap();
for (int i=0; i< arr.size(); i++) {
int i1 = i+1;
int n = arr.get(i);
int otherN = m-n;
if (numsIndex.containsKey(otherN)) {
int otherIndex = numsIndex.get(otherN);
// System.out.printf("a:%d @ %d b:%d @ %d \n",n,i1,otherN,otherIndex);
if (i1 <= otherIndex) {
results.add(i1);
results.add(otherIndex);
} else {
results.add(otherIndex);
results.add(i1);
}
}
// after search or we get ourselves
numsIndex.put(n, i1);
}
return results;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment