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
#6
It works. I tested the function that runs in linear time against my quadratic-time solution 10,000 times, and both give the same result, no matter what integers are in the array:

import random

# Given an array of integers, find the maximum sum
# of all possible contiguous subarrays of the array

def max_subarray_sum_quadratic(arr):
    max_sum = 0
    for mindex in range(0, len(arr)):
        for maxdex in range(mindex + 1, len(arr) + 1):
            subarray_sum = 0
            for each_int in arr[mindex:maxdex]:
                subarray_sum += each_int
            if subarray_sum > max_sum:
                max_sum = subarray_sum
    return max_sum

def max_subarray_sum_linear(arr):
    running_totals = []
    running_total = 0
    for value in arr:
        if value > -running_total:
            running_total += value
        else:
            running_total = 0
        running_totals.append(running_total)
    return max(running_totals)


for r in range(10000):
    whole_array = []
    for r2 in range(6):
        whole_array.append(random.randint(-100, 100))
    if max_subarray_sum_quadratic(whole_array) != max_subarray_sum_linear(whole_array):
        print("\nArray:", whole_array)
        print(max_subarray_sum_quadratic(whole_array), "quadratic")
        print(max_subarray_sum_linear(whole_array), "linear")
Now I just have to figure out how the linear-time function is working exactly. I'm slow at math.
Reply


Messages In This Thread
RE: In linear time, find the maximum sum of all possible contiguous subarrays - by Exsul1 - Oct-02-2019, 09:02 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,253 Mar-05-2021, 04:08 PM
Last Post: SANJIB
  Find frequencies of an audio file at a specific time via librosa jberesford123__ 0 2,383 Oct-21-2020, 01:18 PM
Last Post: jberesford123__
  Find data using a period of time in SQLITE3 SmukasPlays 2 2,226 Jul-30-2020, 02:02 PM
Last Post: SmukasPlays
  Find if time is between start and end time mikke3141 3 2,313 Jan-03-2020, 08:48 PM
Last Post: mikke3141
  Find Maximum Flow for graph with infinite capacities Dav 6 4,342 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