0

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 Answers1

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 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)
Hanjoung Lee
  • 2,123
  • 1
  • 12
  • 20