HaskellWiki

Haskell | Wiki community | Recent changes
Random page | Special pages

 

Not logged in
Log in | Help

Haskell Quiz/Maximum Sub-Array/Solution Kristof

< Haskell Quiz | Maximum Sub-Array

This solution uses a left fold to find the maximum sum. It keeps track of the maximum sublist found so far (the list max and it's sum sum), and the maximum sublist that contains the current position (r and rsum).

max_sublist l = reverse $ fst $ foldl find_max ([],(0,[],0)) l where
  find_max (max, (sum, r, rsum)) x = (max', (sum', r', rsum'))
    where
    (r', rsum')  = if (rsum > 0)
                   then (x:r, rsum+x)
                   else ([x], x)
    (max', sum') = if (rsum' > sum)
                   then (r', rsum')
                   else (max, sum)

Retrieved from "http://www.haskell.org/haskellwiki/Haskell_Quiz/Maximum_Sub-Array/Solution_Kristof"

This page has been accessed 395 times. This page was last modified 19:50, 11 August 2007. Recent content is available under a simple permissive license.