最大子组和
【题目】已知一个整数数组(可能有正数,也有负数),求它的一个连续的子数组,要求该子数组的和为最大。这样的问题称为最大子组和
问题。
如果用最普通的解法,考虑所有可能的子数组,分别对其求和,再从这些和中取最大的一个就行了。其时间复杂度为 O( n 3 n^3 n3)。
haskell 实现这种想法也很容易:
import Data.List (tails,inits)
maxSub :: [Int] -> Int
maxSub la = maximum [sum x | x <- f la]
where
f xs = concat [inits ys| ys <- tails xs]
main :: IO ()
main = print $ maxSub [2,-1