用lua从写一次最大子数组问题

这回由于Lua 的语法比较强大,所以直接写出代码 别的不多说了,我们可以看到lua写这种逻辑是多么有快感。可以返回多个值,使算法看起来是这么的自然。

附上源代码:


function FIND_CROSSING_SUBARRAY (A,low,mid,high)
	local left_sum = -10000;
	local sum = 0;
	local max_left;
	
	local i;
	for i= mid,low,-1 do
		sum = sum + A[i];
		if sum>left_sum then
			left_sum = sum;
			max_left = i;
		end	
	end
	
	local right_sum = -10000;
	local sum = 0;
	local max_right;
	
	for j = (mid+1),high,1 do
		sum = sum + A[j];
		if sum >right_sum then
		right_sum = sum;
		max_right = j;	
		end
	end
	return max_left,max_right,left_sum+right_sum
end




function FIND_MAXIMUM_SUBARRAY (A,low,high)
	
	if high == low then
		return low,high,A[low]	
	else
		local mid = math.floor((low+high)/2);  


		local left_low,left_high,left_sum = FIND_MAXIMUM_SUBARRAY(A,low,mid);


		local right_low,right_high,right_sum= FIND_MAXIMUM_SUBARRAY(A,mid+1,high);


		local cross_low,cross_high,cross_sum= FIND_CROSSING_SUBARRAY(A,low,mid,high);
		
		
		if left_sum>=right_sum then
			if left_sum>=cross_sum then
				return left_low,left_high,left_sum
			end
		end
		
		if(right_sum>=left_sum)then
			if (right_sum>=cross_sum)  then
				return right_low,right_high,right_sum
			end
		end
		
		return cross_low,cross_high,cross_sum
	end
end


B={-100,79,89,201,-211,98,99,201,304,-432};
local left,right,maxvalue= FIND_MAXIMUM_SUBARRAY(B,1,10);
print(left," ",right," ",maxvalue);


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值