kadane algorithm
kadane algorithm
Algorithm
1 2 3
There are n*(n+1)/2 non-
1
empty subarrays
1 2
1 2 3
2 3
3
Problem
Statement
Given an array arr[] of size N. The task is to find the
sum of the contiguous subarray within a arr[] with
the largest sum.
First think the Brute
Force
Algorithm 2: (time complexity O(n^2))
It is easy to make Algorithm 1 more efficient by removing one loop from it. This is possible by
calculating the sum at the same time when the right end of the subarray moves. The result is
the following code
int best = 0;
for (int a = 0; a < n; a++) {
int sum = 0;
for (int b = a; b < n; b++) {
sum += array[b];
best = max(best,sum);
}
}
cout << best << "\n";
Kadane’s
Algorithm:
int ans = a[0], sum = 0;
for (int r = 0; r < n; ++r) {
sum += a[r];
ans = max(ans, sum);
sum = max(sum, 0);
}
Dry Run of above
problem
ans=- ans=- ans= ans= ans= ans= ans= ans=
2 2 4 4 4 4 7 7
sum= sum= sum= sum= sum= sum= sum= sum=
-2
-2 -3
-3 44 3-1 1-2 21 75 4-3
4+(-1)+(-
2)+1+5=7
Maximum Contiguous Array Sum
is 7
Finding minimum subarray
sum
Algorithm:
1.Invert the values of all the elements
2.Follow the procedure of kadane algorithm
and
find largest subarray sum
3.Give result after inverting
Code:
for(int i=0;i<n;i++){
a[i]=-a[i];
}
int ans = a[0], sum = 0;
for (int r = 0; r < n; ++r) {
sum+= a[r];
ans = max(ans, sum);
sum = max(sum, 0);
}
ans=-ans;
Happy
Learning
;)