
Finding Maximum Subarray Sum Using Kadane’s Algorithm in Python
Problem Explanation You are given an integer array arr[] . Your task is to find the maximum sum of a contiguous subarray (subarray must contain at least one element). A subarray is a continuous part of the array. Example: Input: arr = [2, 3, -8, 7, -1, 2, 3] Output: 11 Explanation: Subarray [7, -1, 2, 3] has the maximum sum. Input: arr = [-2, -4] Output: -2 Method Used: Kadane’s Algorithm Kadane’s Algorithm helps us find the maximum subarray sum in a single pass . Idea: Keep adding elements to a running sum If the sum becomes negative, reset it Track the maximum sum seen so far Why This Method? Time complexity: O(n) Space complexity: O(1) Very efficient compared to brute force ( O(n²) ) Widely used in real-world problems Python Code with Explanation class Solution : def maxSubarraySum ( self , arr ): Defines the function to find the maximum subarray sum. max_sum = arr [ 0 ] Initialize max_sum with the first element. This handles cases where all elements are negative. current_sum = 0 Th
Continue reading on Dev.to Python
Opens in a new tab



