Objective: Find the contiguous subarray within a given array that has the maximum sum using Kadane's algorithm.
Kadane's algorithm is a dynamic programming approach that efficiently solves this problem in O(n) time, where n is the number of elements in the array.
max_ending_here: Stores the maximum sum of a contiguous subarray ending at the current index.max_so_far: Stores the overall maximum sum of a contiguous subarray found so far.arr[i]) is greater than max_ending_here + arr[i], start a new subarray from the current element:max_ending_here = arr[i].max_ending_here = max_ending_here + arr[i].max_ending_here with max_so_far.max_ending_here is larger, update max_so_far:max_so_far = max(max_so_far, max_ending_here).max_so_far contains the maximum sum of a contiguous subarray.Input Array:
[-2, 1, -3, 4, -1, 2, 1, -5, 4]
-2
max_ending_here = -2max_so_far = -21
max_ending_here = 1max_so_far = 1-3
max_ending_here = -2max_so_far = 14
max_ending_here = 4max_so_far = 4-1
max_ending_here = 3max_so_far = 42
max_ending_here = 5max_so_far = 51
max_ending_here = 6max_so_far = 6-5
max_ending_here = 1max_so_far = 64
max_ending_here = 5max_so_far = 6Maximum Sum of a Contiguous Subarray: 6
https://leetcode.com/problems/maximum-subarray/description/
Loading component...
Loading component...