Created
July 31, 2021 04:04
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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