4.1 The maximum-subarray problem
- divide-and-conquer
- Divide the problem into a number of subproblems that are smaller instances of the same problem.
- Conquer the subproblems by solving them recursively. If the subproblem sizes are small enough, however, just solve the subproblems in a straightforward manner.
- Combine the solutions to the subproblems into the solution for the original problem.
- The maximum-subarrary problem’s code by C:
- MERGE-SORT
#include <stdio.h>
#define M 5
typedef struct _node{
int left;
int right;
int value;
}Node;
Node search(int left,int right);
int num[M]={-13,3,-25,20,25};
int main(void)
{
Node tmp = search(0,M-1);
printf("the max value is: %d\n",tmp.value);
printf("left is: %d right is: %d",tmp.left,tmp.right);
return 0;
}
Node search(int left,int right)
{
Node tmp = {0,0,0};
if(left==right)
{
tmp.left = left;
tmp.right = right;
tmp.value = num[left];
}
else if(left<right)
{
int mid = (left+right)/2;
int i=0,j=0,k=0,maxV=-1;
Node leftN = search(left,mid);
Node rightN = search(mid+1,right);
Node centerN;
for(i=mid,k=0,maxV=-999999;i>=left;i--)
{
k+=num[i];
if(k>maxV)
{
maxV = k;
centerN.left = i;
}
}
centerN.value=maxV;
for(i=mid+1,k=0,maxV=-999999;i<=right;i++)
{
k+=num[i];
if(k>maxV)
{
maxV = k;
centerN.right = i;
}
}
centerN.value+=maxV;
tmp = leftN.value>=rightN.value?leftN:rightN;
tmp = tmp.value>=centerN.value?tmp:centerN;
}
return tmp;
}
- Brute-Force
#include <stdio.h>
int a[16]={13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
int main()
{
int n,i,j,k,sum=0,max=-99999;
for(i=0;i<16;i++)
{
sum=a[i];
for(j=i+1;j<16;j++)
{
sum=sum+a[j];
if(max<sum)
{
max=sum;
k=j;
n=i;
}
}
}
printf("%d %d %d",n,k,max);
return 0;
}
- linear(DP)
#include <stdio.h>
int a[16]={13,-3,-25,20,-3,-16,-23,18,20,-7,12,-5,-22,15,-4,7};
int main()
{
int n,i,max_i,sum,max;
max=sum=max_i=a[0];
for(i=1;i<16;i++)
{
if(a[i]>=sum+a[i])
{
max_i=a[i];
}
else if(a[i]<sum+a[i])
{
max_i=sum+a[i];
}
if(max<max_i)
{
max=max_i;
}
sum=max_i;
}
printf("%d",max);
}
There is an excellent blog about the maximun-subarry problem: click here