1
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 开始 :)

4

1 回答 1

2

lua 中的数组从 1 开始索引,而不是从 0 开始

local runningSum = array[0]应该local runningSum = array[1] 和也j = 1

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

for i = 1, len, 1 do
于 2012-10-16T09:02:08.393 回答