diff --git a/scripts/kadanes_algorithm.py b/scripts/kadanes_algorithm.py new file mode 100644 index 0000000000..4c4ffdb0c1 --- /dev/null +++ b/scripts/kadanes_algorithm.py @@ -0,0 +1,90 @@ +""" +Kadane's Algorithm - Maximum Subarray Sum + +This algorithm finds the contiguous subarray within a one-dimensional +array of numbers which has the largest sum. + +Time Complexity: O(n) +Space Complexity: O(1) + +Author: kl2400033266 +Issue: #8756 +""" + +def kadanes_algorithm(arr): + """ + Find the maximum sum of a contiguous subarray using Kadane's Algorithm. + + Args: + arr: List of integers + + Returns: + Maximum sum of contiguous subarray + """ + if not arr: + return 0 + + max_current = arr[0] + max_global = arr[0] + + for i in range(1, len(arr)): + max_current = max(arr[i], max_current + arr[i]) + if max_current > max_global: + max_global = max_current + + return max_global + + +def kadanes_with_indices(arr): + """ + Find maximum subarray sum along with start and end indices. + + Args: + arr: List of integers + + Returns: + Tuple of (max_sum, start_index, end_index) + """ + if not arr: + return 0, -1, -1 + + max_current = arr[0] + max_global = arr[0] + start = end = temp_start = 0 + + for i in range(1, len(arr)): + if arr[i] > max_current + arr[i]: + max_current = arr[i] + temp_start = i + else: + max_current = max_current + arr[i] + + if max_current > max_global: + max_global = max_current + start = temp_start + end = i + + return max_global, start, end + + +# Example usage and testing +if __name__ == "__main__": + # Test case 1: Mixed positive and negative numbers + arr1 = [-2, 1, -3, 4, -1, 2, 1, -5, 4] + print(f"Array: {arr1}") + print(f"Maximum Subarray Sum: {kadanes_algorithm(arr1)}") + + max_sum, start, end = kadanes_with_indices(arr1) + print(f"Maximum Sum: {max_sum}, Subarray: {arr1[start:end+1]}") + print() + + # Test case 2: All negative numbers + arr2 = [-5, -3, -1, -4, -2] + print(f"Array: {arr2}") + print(f"Maximum Subarray Sum: {kadanes_algorithm(arr2)}") + print() + + # Test case 3: All positive numbers + arr3 = [1, 2, 3, 4, 5] + print(f"Array: {arr3}") + print(f"Maximum Subarray Sum: {kadanes_algorithm(arr3)}")