Skip to content

Instantly share code, notes, and snippets.

@denisshevchenko
Last active August 19, 2016 18:29
Show Gist options
  • Save denisshevchenko/be576106a5bc4cda770fc10f67e9353e to your computer and use it in GitHub Desktop.
Save denisshevchenko/be576106a5bc4cda770fc10f67e9353e to your computer and use it in GitHub Desktop.
{-# LANGUAGE MultiWayIf #-}
module Main where
main :: IO ()
main = print $ maxLength [10, 9, 2, 3, 4, 6] 500
maxLength :: [Int] -> Int -> Int
maxLength numbers aLimit = collector numbers aLimit []
where
collector :: [Int] -> Int -> [[Int]] -> Int
collector [] _ subArrays = maximum [length sa | sa <- subArrays]
collector (x:xs) k subArrays =
if | x > k -> collector xs k subArrays
| x == k -> collector xs k $ subArrays ++ [[x], []]
| otherwise ->
let subArray = if null subArrays then [x] else last subArrays ++ [x]
in if sum subArray > k
then collector xs k $ subArrays ++ [[x]]
else collector xs k $ replaceLastBy subArray subArrays
where
replaceLastBy sArray sArrays =
if null sArrays then [sArray] else init sArrays ++ [sArray]
@denisshevchenko
Copy link
Author

denisshevchenko commented Aug 19, 2016

It's the easiest solution, without reading of stdin. I've checked it with different lists and limits - it works. In the real life I'd write some test (a-la QuickCheck) to prove it works.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment