Find the index of the subarray whose sum is minimum

吃可爱长大的小学妹 提交于 2021-01-29 08:01:15

问题


Given an array of length n, with integers(can be negative or positive). Find the starting and ending index of the subarray with minimum sum possible.


回答1:


As you specified this is about Kadanes Algorithm, it is easy to find a lot of references about it. GeeksForGeeks : Smallest sum contiguous subarray kindly explains about the algorithm and provides implementations in a few languages.

Based on the python code from that page, I have revised it to return begin/end indices rather than the sum value. The idea is keeping the range indices along with the sum value.

import sys

def smallestSumSubarr(arr, n):
    min_ending_here = sys.maxint
    min_so_far = sys.maxint
    min_so_far_range = (-1, 0) # save indices

    for i in range(n):
        if (min_ending_here > 0):
            min_ending_here = arr[i]
            min_ending_here_range = (i, i) # start over
        else:
            min_ending_here += arr[i]
            min_ending_here_range = (min_so_far_range[0], i) # extend the range

        if min_so_far > min_ending_here: # update both value and range
            min_so_far = min_ending_here
            min_so_far_range = min_ending_here_range

    return min_so_far_range # return range instead of value


# Usage
arr = [3, -4, 2, -3, -1, 7, -5]
n = len(arr)
print "Smallest sum range(inclusive): ", smallestSumSubarr(arr, n)

On STDOUT, you will see

Smallest sum range(inclusive):  (1, 4)


来源:https://stackoverflow.com/questions/54759904/find-the-index-of-the-subarray-whose-sum-is-minimum

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!