Last active
August 19, 2016 18:29
-
-
Save denisshevchenko/be576106a5bc4cda770fc10f67e9353e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.