Kadane Algorithm TakeUForward Task
Kadane Algorithm TakeUForward Task
In programming terms, you are given an array of integers (both positive and negative), and
you must find a contiguous subarray (i.e., sequence of elements without breaks) that has the
maximum possible sum.
1. Steps:
Formula:
currentSum = max(currentElement, currentSum + currentElement)
maxSum = max(maxSum, currentSum)
0 -2 -2 -2
1 1 1 1
2 -3 -2 1
3 4 4 4
4 -1 3 4
5 2 5 5
6 1 6 6
7 -5 1 6
8 4 5 6
C++
Java
Python
def maxSubArray(nums):
max_sum = current_sum = nums[0]
for num in nums[1:]:
current_sum = max(num, current_sum + num)
max_sum = max(max_sum, current_sum)
return max_sum
JavaScript
function maxSubArray(nums) {
let maxSum = nums[0], currentSum = nums[0];
for (let i = 1; i < nums.length; i++) {
currentSum = Math.max(nums[i], currentSum + nums[i]);
maxSum = Math.max(maxSum, currentSum);
}
return maxSum;
}