/*
*function: divide and conquer algorithm
* time complexity of the problem solving
*/
#include <stdio.h>
#define N 10
int maxnum(int *, int, int);
int max(int, int);
int max_3(int, int, int);
int max_3(int a, int b, int c)
{
return ((a > b ? a : b) > c ? (a > b ? a : b) : c);
}
int max(int data1, int data2)
{
return (data1 > data2 ? data1 : data2);
}
int maxnum(int data[], int low, int high)
{
int mid, num, i;
int rmax, lmax;
if( low > high ) //if no element is returned to 0
return 0;
if( low == high ) //there is only one element
return max(0, data[0]);
mid = (low + high) / 2;
/*find max crossing to right*/
rmax = num = 0;
for(i = mid + 1; i <= high; i++){
num += data[i];
rmax = max(rmax, num);
}
/*find max crossing to left*/
lmax = num = 0;
for(i = mid; i >= low; i--){
num += data[i];
lmax = max(lmax, num);
}
return max_3( lmax + rmax, maxnum(data, low, mid), maxnum(data, mid + 1, high) );
}
int main(int argc, char *argv[])
{
int data[N] = {31, -41, 59, 26, -53, 58, 97, -93, -23, 84};
int low = 0, high = N - 1;
int max;
max = maxnum(data, low, high);
/*Output*/
printf("%d\n", max);
return 0;
}
|