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 = -2
max_so_far = -2
1
max_ending_here = 1
max_so_far = 1
-3
max_ending_here = -2
max_so_far = 1
4
max_ending_here = 4
max_so_far = 4
-1
max_ending_here = 3
max_so_far = 4
2
max_ending_here = 5
max_so_far = 5
1
max_ending_here = 6
max_so_far = 6
-5
max_ending_here = 1
max_so_far = 6
4
max_ending_here = 5
max_so_far = 6
Maximum Sum of a Contiguous Subarray: 6
https://leetcode.com/problems/maximum-subarray/description/
Loading component...
Loading component...
INPUT: [-2 , 1, -3 , 4, -1, 2 , 1, -5 ,4]
OUTPUT: 6
public static void main(String[] args) {
int[] arr = {2, 3, -8, 7, -1, 2, 3};
System.out.println(maxsubArraySum(arr));
}//function end
static int maxsubArraySum(int[] arr) {
int res = arr[0];
for (int i = 0; i < arr.length; i++) {
int currSum = 0;
for (int j = i; j < arr.length; j++) {
currSum = currSum + arr[j];
res = Math.max(res, currSum);
}//Loop End
}//Loop End
return res;
}//function end
Utility Function is not required.