Well, the answer for an array of all negative numbers is to choose no elements, or if you must choose one, to choose the maximum single element. But presumably you solve it with the normal algorithm but with one level of look-behind. Something like,
function maxsum(arr)
local max2 = function(a, b) if a > b then return a else return b end end
local max3 =
function(a, b, c)
if a > b and a > c then return a
elseif b > c then return b
else return c end end
local best = 0
local best_here = 0
local i = 2
while i <= table.maxn(arr) do
best_here = max3(0, best_here + arr[i], best_here + arr[i-1])
best = max2(best, best_here)
if arr[i] > arr[i-1] then i = i + 2 else i = i + 1 end
end
return best
end
print(maxsum{1, -1, 2, -2, 3, -3, -4, 4, -5})
Assuming this algorithm is correct (it worked for my couple of test cases), the main trickiness is that you have to skip two elements if you choose the current one, to make sure that you don't double-choose.