鉴于整数数组,你怎么能找到两个指数,i和j,使得在子阵列元素的总和开始到结束的索引最大化, 以线性时间 ?
从我的编程珍珠副本中:
maxsofar = 0 maxendinghere = 0 for i = [0, n) /* invariant: maxendinghere and maxsofar are accurate are accurate for x[0..i-1] */ maxendinghere = max(maxendinghere + x[i], 0) maxsofar = max(maxsofar, maxendinghere)