I wrote the following code to find the contiguous subarray with maximum sum, which I tink pretty ugly:
The problem is my internal thinking of this problem (using DP) is imperative. How can I refactor this piece of code and make it more functional (and DRY)? Any recommendations on how to think algorithms in functional language? (maybe should be a sperate question though).
class Object
def sum(lst)
lst.reduce(:+)
end
end
def dp_max_subarray(lst)
i=0
s=0
while i<lst.length
(i...lst.length).each do |j|
t = sum lst[i..j]
if t > s
s= sum lst[i..j]
next
elsif t < 0
i=j+1
break
end
end
i+=1
end
s
end
Look here for a O(n) Python solution. Translating it to functional Ruby is straightforward: