Given a array of natural numbers, we have to find the maximum interval sum.
5 5 -1 5 5
Now we have these intervals (5 + 5), ( 5 + 5 + (-1)), (5 + 5 + (-1) + 5), (5 + 5 + (-1) + 5 + 5).
Which interval has maximum sum?
(5 + 5) = 10
( 5 + 5 + (-1)) = 9
(5 + 5 + (-1) + 5) = 14
(5 + 5 + (-1) + 5 + 5) = 19
So, the last interval has maximum sum. These type of problems are called Maximum Interval Sum.
C++ implementation:
#include <iostream>
using namespace std;
const int INF = (-(1<<30)); // negative infinity
int MIS( ) {
sum = 0; // initially sum is 0
Max = -INF; // Maximum is less than 0
for( i=0; i<N; i++ ) {
sum += A[i]; // "A[]" array of intejars
if( sum > Max ) Max = sum;
if( sum < 0 ) sum = 0; // sum below 0 is not useful, right?
}
return Max;
}