Suppose we change the definition of the maximum subarray problem to allow the result to be an empty subarray, where the sum of the values of an empty subarray is 0. How would you change any of the algorithms that do not allow empty subarrays to permit an empty subarray to be the result.
FIND-MAXIMUM-SUBARRAY 最后一部分的伪代码是
if left-sum >= right-sum && left-sum >= cross-sum return (left-low, left-high, left-sum) if right-sum >= left-sum && right-sum >= cross-sum return (right-low, right-high, right-sum) else return (cross-low, cross-high, cross-sum
把伪代码改成
if left-sum >= right-sum && left-sum >= cross-sum && left-sum > 0 return (left-low, left-high, left-sum) if right-sum >= left-sum && right-sum >= cross-sum && right-sum > 0 return (right-low, right-high, right-sum) if cross-sum >= left-sum && cross-sum >= right-sum && cross-sum > 0 return (cross-low, cross-high, cross-sum) else return (0, 0, 0)
Use the following ideas to develop a nonrecursive, linear-time algorithm for the maximum-subarray problem. Start at the left end of the array, and progress toward the right, keeping track of the maximum subarray seen so far. Knowing a maximum subarray of A[1..j], extend the answer to find a maximum subarray ending at index j+1 by using the following observation: a maximum subarray of A[1..j+1] is either a maximum subarray of A[1..j] or a subarray A[i..j+1], for some 1 <= i <= j + 1. Determine a maximum subarray of the form A[i..j+1] in constant time based on knowing a maximum subarray ending at index j.
代码链接