Ice Cream Parlor

  • + 0 comments

    A more elegant O(n) solution, similar to cb_kalz's solution (Scala):

      def icecreamParlor(m: Int, arr: Array[Int]): Array[Int] = {
        arr.zip(1 to Int.MaxValue).foldLeft((None: Option[Array[Int]], Map.empty[Int, Int])) {
          case ((result @ Some(_), acc), _) => (result, acc)
          case ((None, acc), (elem1, i)) =>
            val elem2 = m - elem1
            if (acc.contains(elem2)) (Some(Array(acc(elem2), i).sorted), acc)
            else (None, acc + (elem1 -> i))
        }._1.get
      }