Closed blade-sensei closed 4 years ago
Kadane Algorithm is used to get the maximal sum of contiguous subarray.
Basically we need to compare EACH sum of subarrays.
. Example:
principal array --> [-2, 10, 2, -12]
> one of contiguous subarray is [2, -12]
- is its part of the principal array
- is it composed by [2] [-12] that are next each other
> [10, -12] is a non contiguous subarray: don't respect second criteria
The main idea behind Kadane algorithm is to resolve smallest problem by one one. So the idea:
as a subarray can also be composed by one element like [10] an index = subarray[index]
/**
* if [-2, 10, 2, -12]
* >
* In a classic brute force we change device the contiguous subarray this way:
* 1 -> [-2] [-2,10] [-2,10, 2] [-2,10,2,-12]
*2 -> [10] [10,2] [10,2,-12]
*3 -> [2] [2,-12]
*4 -> [-12]
*
**/
We can use the same structure for Kadane algorith we considered that we have 4 POTENTIALY max sum of each LEVEL.
Depends on the specific conditions be have 2 GLOBAL ways to resolve tihs.
First approch
Consideres that for each iteration we compute the MAX_SUM unti index [i].
First To do that we need to SUM of the contiguous subarray[i], We should not forget that [i] is also a subarray (of only 1 element). So we compute the the maximal the current_sum and the current element [i] (line 1 below). Now we know which if the subarray_sum is max (current_sum or [i]. But we still don't compare with [previous_sum] (subarray[i -1]) that can be greater than the current_sum. So compute this
globalMax = Math.max(globalMax, currentMax);
if this is first element or array of single element. the previousGlobalmax will be -infinity, to return the single element but in case it's negative it will works. Now this result is returned, globalMax will also be used for the next subarray[+1, +2..]Important ❌
In summary ech iteration will have 3 the options of MAX_SUM at this [index]
currentMax = Math.max(currentMax + number, nuber);
globalMax = Math.max(globalMax, currentMax);
Second approch
We considere that if we get negatives as sum if a subarray. the next contigious subarrays are not neccessary anymore to be calculated. Cause this negative subarray will decrease the max_sum. So we dont need to keep this subarray. Another sum subarray will be greater, so to start another sum we reset the sum_max to 0, this way, next iteration will set sum_max = sum_max + i, it means that we start another sum from i.