We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
1) Simply hash each price differential to its index. 2) find the first price which fulfills the addend. Example in Java 17:
/** * Find two prices in a list which sum to to 'm'. * Simply subtract each price from 'm', then find the first * price which matches as augend. * * 𝚯(N) runtime for N prices * 𝚯(N) space * * @param arr prices to choose from * @param m total funds available * @return sorted indices of the two chosen items */publicstaticList<Integer>icecreamParlor(intm,List<Integer>arr){Map<Integer,Integer>addends=range(0,arr.size()).boxed().collect(toMap(i->m-arr.get(i),i->++i,(x,y)->x));intindex=1;for(Integerprice:arr){Integermatch=addends.get(price);if(match!=null&&index!=match)returnStream.of(match,index).sorted().toList();index++;}thrownewIllegalStateException();}
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Ice Cream Parlor
You are viewing a single comment's thread. Return to all comments →
1) Simply hash each price differential to its index. 2) find the first price which fulfills the addend. Example in Java 17: