Dynamic programming aspect in Kadane's algorithm

后端 未结 2 1648
忘掉有多难
忘掉有多难 2021-01-31 10:39
Initialize:
    max_so_far = 0
    max_ending_here = 0

Loop for each element of the array
   (a) max_ending_here = max_ending_here + a[i]
   (b) if(max_ending_here <         


        
2条回答
  •  天命终不由人
    2021-01-31 11:09

    Note that I derived my explanation from this answer. It demonstrates how Kadane’s algorithm can be seen as a DP algorithm which has overlapping subproblems.

    Identifying subproblems and recurrence relations

    Imagine we have an array a from which we want to get the maximum subarray. To determine the max subarray that ends at index i the following recursive relation holds:

    max_subarray_to(i) = max(max_subarray_to(i - 1) + a[i], a[i])
    

    In order to get the maximum subarray of a we need to compute max_subarray_to() for each index i in a and then take the max() from it:

    max_subarray = max( for i=1 to n max_subarray_to(i) )
    

    Example

    Now, let's assume we have an array [10, -12, 11, 9] from which we want to get the maximum subarray. This would be the work required running Kadane's algorithm:

    result = max(max_subarray_to(0), max_subarray_to(1), max_subarray_to(2), max_subarray_to(3))
    
    max_subarray_to(0) = 10  # base case
    max_subarray_to(1) = max(max_subarray_to(0) + (-12), -12)
    max_subarray_to(2) = max(max_subarray_to(1) + 11, 11)
    max_subarray_to(3) = max(max_subarray_to(2) + 9, 49)
    

    As you can see, max_subarray_to() is evaluated twice for each i apart from the last index 3, thus showing that Kadane's algorithm does have overlapping subproblems.

    Kadane's algorithm is usually implemented using a bottom up DP approach to take advantage of the overlapping subproblems and to only compute each subproblem once, hence turning it to O(n).

提交回复
热议问题