0

What is the most efficient way to calculate the most negative sum for any set of consecutive indexes in an array? You can take any consecutive group of positive and negative integers in an array to create the most negative sum possible.

For example you have arr = [10, -15, 2, 25, -16, -53, 22, 2, 1, -3, 60] the most negative sum is -69 from summing -16 and -53.

Another example you have arr = [10, -15, -2, 10, -16, -53, 22, 2, 1, -3, 60] the most negative sum is -76 from summing -15, -2, 10, -16, -53.

4
  • You can use a modified version of Kadane's Algorithm. Commented May 18, 2021 at 7:04
  • you need to modified Kadane's algorithm Commented May 18, 2021 at 7:05
  • sum value of -15, -2, 10, -16, -53 is -76, not -78 Commented May 18, 2021 at 7:23
  • yeah sorry it's late by me :( Commented May 18, 2021 at 7:33

1 Answer 1

3

You can use the standard Kadane’s algorithm, just change the sign of array element.

def kadane(arr):
    max_so_far = float('-inf')
    max_ending_here = 0

    for i in range(0, len(arr)):
        arr[i] = arr[i] * -1
        max_ending_here = max_ending_here + arr[i]
        if max_so_far < max_ending_here:
            max_so_far = max_ending_here

        if max_ending_here < 0:
            max_ending_here = 0
    return max_so_far


print(kadane(arr=[10, -15, 2, 25, -16, -53, 22, 2, 1, -3, 60]) * -1)  # -69
print(kadane(arr=[10, -15, -2, 10, -16, -53, 22, 2, 1, -3, 60]) * -1) # -76
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.