Skip to content

Commit 36dc59a

Browse files
committed
Maximum Subarray Sum - Kadane's algorithm
1 parent c574d67 commit 36dc59a

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

src/Maths/KadaneAlgorithm.hs

+36
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
module Maths.KadaneAlgorithm where
2+
3+
-- Sample Input List
4+
inputList :: [Integer]
5+
inputList = [1, -2, 3, 4, -5, 6, -7, 8, 9, 10]
6+
7+
8+
-- Helper function that updates values of maxSoFar and maxEndingHere
9+
-- and call itself recursively over the values of the list
10+
-- and when the list is empty, return the maxSoFar value
11+
-- with the start and end indices.
12+
maxSubArrayHelper :: Integer -> Integer -> Integer -> Integer -> Integer -> [Integer] -> (Integer, Integer, Integer)
13+
maxSubArrayHelper maxSoFar _ _ start end [] = (maxSoFar, start, end)
14+
maxSubArrayHelper maxSoFar maxEndingHere i start end (x:xs) =
15+
let i' = i + 1
16+
maxEndingHere' = maxEndingHere + x
17+
in
18+
if maxSoFar < maxEndingHere' then
19+
maxSubArrayHelper maxEndingHere' maxEndingHere' i' start i xs
20+
else if maxEndingHere' < 0 then
21+
maxSubArrayHelper maxSoFar 0 i' i' i' xs
22+
else
23+
maxSubArrayHelper maxSoFar maxEndingHere' i' start end xs
24+
25+
-- Initially maxSoFar (maximum sum till the previous iteration),
26+
-- maxEndingHere (maximum sum till end index of the current iteration),
27+
-- start (start index) and end (end index) are sent as 0
28+
maxSubArray :: [Integer] -> (Integer, Integer, Integer)
29+
maxSubArray = maxSubArrayHelper 0 0 0 0 0
30+
31+
-- Outputs (sum, start, end)
32+
-- sum - sum from start to end indices of the input array
33+
-- start:end - the subarray with max sum
34+
main :: IO ()
35+
main = do
36+
print (maxSubArray inputList)

0 commit comments

Comments
 (0)