Python Forum
In linear time, find the maximum sum of all possible contiguous subarrays
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
In linear time, find the maximum sum of all possible contiguous subarrays
#10
import random

def mymax(array):
    '''Find sub-array of array with the largest sum.
    Return (sum, start_index, end_index)
    '''
    subsum = start = 0
    maxsum = [subsum, start, start]
    for index, value in enumerate(array):
        subsum += value
        if subsum > maxsum[0]:
            # Found a new maximum
            maxsum = [subsum, start, index]
        elif subsum <= 0:
            # No future maxsums will contain anything from array[:index].  Look for max sub_array sum for array[i+1:]
            subsum = 0
            start = index + 1
    return maxsum

def gribmax(array):
    '''Solution from Griboullis for finding greatest sum of consecutive array values'''
    mv = sv = best = 0
    for value in array:
        sv += value
        mv = min(mv, sv)
        best = max(best, sv-mv)
    return best

x = random.choices(range(-100, 100), k=30)
print(x)
print(mymax(x))
print(gribmax(x))
My solution and Griboullis' solution agree when run on 100,000 different random arrays of length 100.
Gribouillis likes this post
Reply


Messages In This Thread
RE: In linear time, find the maximum sum of all possible contiguous subarrays - by deanhystad - Oct-28-2021, 06:18 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  find the header location in a .bin file without reading the whole file at a time SANJIB 0 2,275 Mar-05-2021, 04:08 PM
Last Post: SANJIB
  Find frequencies of an audio file at a specific time via librosa jberesford123__ 0 2,443 Oct-21-2020, 01:18 PM
Last Post: jberesford123__
  Find data using a period of time in SQLITE3 SmukasPlays 2 2,258 Jul-30-2020, 02:02 PM
Last Post: SmukasPlays
  Find if time is between start and end time mikke3141 3 2,352 Jan-03-2020, 08:48 PM
Last Post: mikke3141
  Find Maximum Flow for graph with infinite capacities Dav 6 4,433 Apr-16-2019, 02:08 PM
Last Post: Dav

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020