Ice Cream Parlor

  • + 0 comments

    Java 8 - Used an Index Sort to order the values. One time through the list and to find the correct pair.

        public static List<Integer> icecreamParlor(int m, List<Integer> arr) {
            List<Integer> rtn = new ArrayList<>();
            
            // Index Sort
            int[] indices = IntStream.range(0, arr.size())
                    .boxed()
                    .sorted(Comparator.comparingInt(i -> arr.get(i)))
                    .mapToInt(Integer::intValue)
                    .toArray();
            
            // Close in on the solution
            int l = 0;
            int h = arr.size()-1;
            while(l<h && arr.get(indices[l]) + arr.get(indices[h]) != m) {
                int vh = arr.get(indices[h]);
                int vl = arr.get(indices[l]);
                
                if (vh >= m || (vh + vl) > m)
                    --h;
                else 
                    ++l;           
            }
            
            // sort result into asscending order.
            rtn.add(Math.min( indices[l], indices[h] )+1); 
            rtn.add(Math.max( indices[l], indices[h] )+1); 
            
            return rtn ;
        }