分治算法的概念
1.将一个规模为n的问题,分解成为k个规模较小的子问题,然后依次递归解决子问题,把求得的解合并就得到然问题的解。
2.应用很多。
实例分析--求最大子数组问题
1.上期没搞懂lua的递归,看了一下决定这期使用lua的递归
求 如何购买股票赚最多的钱。一看知道7到 11天赚最多
1.首先暴力求解的方法
--传入价格表
table={100,113,110,85,105,102,86,63,81,101,94,106,101,79,94,90,97}
table2={} --变化表
for i=2,#table do
local difference=table[i]-table[i-1]
table2[i-1]=difference
end
left,right=0,0
function getprofit() --对table2 操作
local max1,sum=table2[1],0--max1 是一轮的最大值
for j=1,#table2 do
for k=j,#table2 do
sum=sum+table2[k]
if(sum>max1) then
max1=sum
left,right=j,k
end
end
sum=0
end
return left,right
end
a,b=getprofit()
print(a-1,b)
求得 7 11没问题
2. 使用分治法分析问题
--最大子数组的结构体
subarray={startindex,endidex,total}
table={100,113,110,85,105,102,86,63,81,101,94,106,101,79,94,90,97}
df={} --变化表
for i=2,#table do
local difference=table[i]-table[i-1]
df[i-1]=difference
end
local getmax;
getmax=function(low,high,arr) --三个参数
if(low==high) then
subarray.startindex=low
subarray.endidex=high
subarray.total=arr[low]
return subarray
end
local mid=(low+high)/2 //低区间[low,mid] 高区间[mid,high]
local sub1,sub2=subarray,subarray
sub1=getmax(low,mid,arr)
sub2=getmax(mid+1,high,arr)
local total1,startindex1,totaltemp=arr[mid],mid,0
for i=mid,low,-1 do
totaltemp=totaltemp+arr[i]
if(totaltemp>total1) then
total1=totaltemp
startindx1=i
end
end
local total2,endidex1=arr[mid+1],mid+1
for j=mid+1,high,1 do
totaltemp=totaltemp+arr[j]
if(totaltemp>total2) then
total2=totaltemp
endindex1=j
end
end
sub3=subarray
sub3.startindex=startindex1;
sub3.endidex=endindex1
sub3.total=total1+total2
if(sub1.total>=sub2.total and sub1.total>sub3.total) then
return sub1
elseif(sub2.total>=sub1.total and sub2.total>sub3.total) then
return sub2
else
return sub3
end
end
getmax(1,#df,df)
结果执行不出来就很气。