假设我们有一个n实数数组。我们希望找到数组中的最长连续子序列,它的和大于或等于零。
必须在线性时间内完成。
我们真的不知道怎么开始回答这个问题。
提前谢谢。
最佳答案
为此,创建一个子序列(这里用ibeg
、iend
和lengthlen
指定),并基本上沿着序列行进,在末尾扩展子序列或在开头缩小子序列以保持>0。由于内环受当前序列长度的约束,所以它仍然是O(N)。
var ibeg = 0;
var iend = 0;
var len = 0;
var best_len = -1, best_ibeg = 0, best_iend = 0;
var acc = 0;
var i = 0;
var N = length(sequence);
while i<N
acc += sequence(i);
len++;
iend++;
if acc>0
if len>best_len
best_len = len;
best_ibeg = ibeg;
best_iend = iend;
end
else
while ibeg<=iend
acc -= sequence(ibeg);
ibeg++;
if acc>0, break; end
end
end
end
然后
best_len
将是最长序列的长度,best_ibeg
和best_iend
将分别是它的开始和结束位置。关于algorithm - 查找具有非负和的最长子序列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24451796/