You can answer this CLRS question, which includes a hint:
Use the following ideas to develop a non-recursive linear time algorithm for the problem with maximum subarability.
Start at the left end of the array and move towards the right, tracking the maximum subarak seen so far.
Knowing the maximum auxiliary array A[1..j] , continue the answer to find the maximum subarax ending in index j+1 using the following observation:
the maximum auxiliary array A[1..j+1] is either the maximum auxiliary array A[1..j] or the auxiliary array A[i..j+1] for some 1 <= i <= j + 1 .
Determine the maximum auxiliary array of form A[i..j+1] in constant time, based on the knowledge of the maximum subaram ending in index j .
max-sum = A[1] current-sum = A[1] left = right = 1 current-left = current-right = 1 for j = 2 to n if A[j] > current-sum + A[j] current-sum = A[j] current-left = current-right = j else current-sum += A[j] current-right = j if current-sum > max-sum max-sum = current-sum left = current-left right = current-right return (max-sum, left, right)
Avi cohen
source share