Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

confusion about Kadane’s Algorithm?

I looked up the optimal solution for finding largest sum of continuous subarray. And there's algorithm called Kadane's algorithm. Here is pseduocode I found on geeksforgeeks.

 Initialize:
     max_so_far = 0
     max_ending_here = 0

 Loop for each element of the array
   (a) max_ending_here = max_ending_here + a[i]
   (b) if(max_ending_here < 0)
             max_ending_here = 0
   (c) if(max_so_far < max_ending_here)
             max_so_far = max_ending_here
 return max_so_far

The part I don't understand is (b), why is max_ending here set to 0 when max_ending here is less than 0?? what's the intuition behind this?

like image 425
I am mad Avatar asked Dec 04 '25 09:12

I am mad


2 Answers

You want to reset the max because of any potential negative array elements that may offset the max.

for example,

2 3 -6 4 2

at element -6, if you don't reset the max here then you carry the max of -1 into the next iteration.

like image 163
夢のの夢 Avatar answered Dec 10 '25 10:12

夢のの夢


If max_ending_here is less than 0 going into part (b), that means that the maximum sum making use of this element is less than 0. There's a better sum than that ending here, which is to just take a length-0 subarray. That's what we do in part (b).

Basically, if we enter the if in part (b), we're throwing away all previous elements and starting the subarray from scratch.

like image 42
user2357112 supports Monica Avatar answered Dec 10 '25 11:12

user2357112 supports Monica



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!