Skip to content

re: Daily Coding Problem #2 VIEW POST


Here is O(N) without division:

arr = (1..5).to_a
a1, a2 =[[1, 1], [[1], [1]]]) do |((ap, rp), (acc, racc)), (av, rv)|
    [[av, rv], [acc << acc.last*ap, racc << racc.last*rp]] { |a| a.drop(1) } { |a| a.reduce(:*) }
#⇒ [120, 60, 40, 30, 24]

The idea is to calculate opposite partial products and then reduce them. In a language that has a proper map_reduce function implemented on enumerables (like Elixir,) that might be done in one step without intermediate variables.

code of conduct - report abuse