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
#29
Hi,

The nested loop approach ("brute force") will produce the goods,
but for the (-100/+100, array = 30) case it will take 24+ seconds.(100_000 iterations)
I set out to see if this approach could be tuned to produce more acceptable results.
And yes, if you prepare the initial array in such a way that it will only
test "valid" candidate subarrays, the processing time drops to +/- 4.8 secs.
(Doubling the arrays : 5-10-20... will roughly double the processing time.)
Looking for inspiration to cut the 4.8 secs further...
maxArr = [max(arr)]
idxStarts, idxEnds = [],[]
for idx, number in enumerate(arr):
    if number > 0:           
        if idx == 0 or arr[idx-1] < 0:
            idxStarts.append(idx)                
        if idx == len(arr)-1 or arr[idx+1] < 0:
            idxEnds.append(idx)
for idxfrom in idxStarts:
    for idxto in idxEnds:
        maxArr.append(sum(arr[idxfrom:idxto +1]))
    maxArr = [max(maxArr)]
It is more important to do the right thing, than to do the thing right.(P.Drucker)
Better is the enemy of good. (Montesquieu) = French version for 'kiss'.
Reply


Messages In This Thread
RE: In linear time, find the maximum sum of all possible contiguous subarrays - by DPaul - Nov-04-2021, 07:37 AM

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,908 Mar-05-2021, 04:08 PM
Last Post: SANJIB
  Find frequencies of an audio file at a specific time via librosa jberesford123__ 0 3,473 Oct-21-2020, 01:18 PM
Last Post: jberesford123__
  Find data using a period of time in SQLITE3 SmukasPlays 2 2,900 Jul-30-2020, 02:02 PM
Last Post: SmukasPlays
  Find if time is between start and end time mikke3141 3 3,181 Jan-03-2020, 08:48 PM
Last Post: mikke3141
  Find Maximum Flow for graph with infinite capacities Dav 6 5,771 Apr-16-2019, 02:08 PM
Last Post: Dav
  Replace with Maximum Value leoahum 4 3,700 Mar-13-2019, 06:24 PM
Last Post: leoahum

Forum Jump:

User Panel Messages

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