最大子段和(三种算法) 的MATLAB求解

最大子段和(三种算法) 的MATLAB求解
最大子段和(三种算法) 的MATLAB求解

最大子段和(三种算法)

1、蛮力法

function [sum,besti,bestj]=MaxSum(v,n)%%蛮力法sum=0;

for i=1:n

thisSum=0;

for j=i:n

thisSum=thisSum+v(j);

if(thisSum>sum)

sum=thisSum;

besti=i;

bestj=j;

end

end

end

if sum<0

sum=0;

End

2、分治法

function sum=MaxSubSum(a,left,right) %分治法

sum=0;

if (left==right)

if a(left)>0

sum=a(left);

return;

else

sum=0;

return;

end

else

center=floor((left+right)/2);

leftsum=floor(MaxSubSum(a,left,center));

rightsum=floor(MaxSubSum(a,center+1,right)); s1=0;

lefts=0;

for i=center:-1:left

lefts=lefts+a(i);

if lefts>s1

s1=lefts;

end

end

s2=0;

rights=0;

for i=center+1:right

rights=rights+a(i);

if rights>s2

s2=rights;

end

end

sum=s1+s2;

if(sum

sum=leftsum;

end

if(sum

sum=rightsum;

end

return;

end

3、动态规划法

function sum=MaxSum1(a,n)%%动态规划法sum=0;

b=0;

for i=1:n

if b>0

b=b+a(i);

else

b=a(i);

end

if b>sum

sum=b;

end

end

相关主题
相关文档
最新文档