Chapter 4 Divide-and-Conquer 4.1 The maximum-subarray problem

4.1 The maximum-subarray problem

  • divide-and-conquer
  1. Divide the problem into a number of subproblems that are smaller instances of the same problem.
  2. Conquer the subproblems by solving them recursively. If the subproblem sizes are small enough, however, just solve the subproblems in a straightforward manner.
  3. Combine the solutions to the subproblems into the solution for the original problem.
  • The maximum-subarrary problem’s code by C:
  1. 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;
}
  1. 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;
}
  1. 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值