实现最大连续和算法

时间:2012-10-16 05:38:00

标签: algorithm lua

function maxContSum(array)
    local len = #array
    local maxSum = 0
    local runningSum = array[0]
    local j = 0
    local start, finish = 0,0
    for i=0, len-1,1 do
        if runningSum > 0 then
            runningSum =runningSum + array[i]
        else 
            runningSum = array[i]
            j = i
        end
        if runningSum > maxSum then
            maxSum = runningSum
            start = j
            finish = i
        end
    print ("maxsum is ", maxSum)
   end
end

a = {-2, 2,3,4,5,-7,8,0,-1,1,2,3,4}
maxContSum(a)

这是我的代码。 但我收到此错误消息:

lua: maxContSum.lua:8: attempt to compare number with nil stack
traceback:
        maxContSum.lua:8: in function 'maxContSum'
        maxContSum.lua:24: in main chunk
        [C]: ?

需要帮助 谢谢!

编辑: 我发现了我的问题。 Lua数组索引从1开始:)

1 个答案:

答案 0 :(得分:2)

lua中的数组是从1而非0

索引的

local runningSum = array[0]应为local runningSum = array[1] 还有j = 1

并且for循环应该从1开始到n

for i = 1, len, 1 do