From 2b64e1803dbd4f2c28b910ce8f2c4f1bc994ea93 Mon Sep 17 00:00:00 2001 From: Tanish22 Date: Sun, 12 Oct 2025 08:21:33 +0530 Subject: [PATCH 1/2] Adding kadane's algorithm to dp/ folder kadane's algorithm is not present in dynamic_programming folder so adding it. --- dynamic_programming/kadane_algorithm.py | 61 +++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 dynamic_programming/kadane_algorithm.py diff --git a/dynamic_programming/kadane_algorithm.py b/dynamic_programming/kadane_algorithm.py new file mode 100644 index 000000000000..39d59dd922e9 --- /dev/null +++ b/dynamic_programming/kadane_algorithm.py @@ -0,0 +1,61 @@ +""" +Kadane's Algorithm implementation in Python. + +Finds the maximum sum of a contiguous subarray within +a one-dimensional array of numbers. + +Source: +https://en.wikipedia.org/wiki/Maximum_subarray_problem +""" + + +def kadane(arr: list[int]) -> tuple[int, list[int]]: + """ + Returns the maximum sum of a contiguous subarray and the subarray itself. + + Parameters + ---------- + arr : list + List of integers (can be positive, negative, or zero). + + Returns + ------- + tuple + Maximum subarray sum and the corresponding subarray. + + Examples + -------- + >>> kadane([-2,1,-3,4,-1,2,1,-5,4]) + (6, [4, -1, 2, 1]) + + >>> kadane([1,2,3,4]) + (10, [1, 2, 3, 4]) + + >>> kadane([-1,-2,-3]) + (-1, [-1]) + """ + if not arr: + raise ValueError("Input array cannot be empty") + + max_current = max_global = arr[0] + start = end = s = 0 + + for i in range(1, len(arr)): + if arr[i] > max_current + arr[i]: + max_current = arr[i] + s = i + else: + max_current += arr[i] + + if max_current > max_global: + max_global = max_current + start = s + end = i + + return max_global, arr[start:end+1] + + +# Doctest runner +if __name__ == "__main__": + import doctest + doctest.testmod() From f0af1b275d96902f9025f7307e97550d718ec958 Mon Sep 17 00:00:00 2001 From: "pre-commit-ci[bot]" <66853113+pre-commit-ci[bot]@users.noreply.github.com> Date: Sun, 12 Oct 2025 02:52:10 +0000 Subject: [PATCH 2/2] [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --- dynamic_programming/kadane_algorithm.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/dynamic_programming/kadane_algorithm.py b/dynamic_programming/kadane_algorithm.py index 39d59dd922e9..757e316c1da8 100644 --- a/dynamic_programming/kadane_algorithm.py +++ b/dynamic_programming/kadane_algorithm.py @@ -52,10 +52,11 @@ def kadane(arr: list[int]) -> tuple[int, list[int]]: start = s end = i - return max_global, arr[start:end+1] + return max_global, arr[start : end + 1] # Doctest runner if __name__ == "__main__": import doctest + doctest.testmod()