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

I gave this "interview question" some considerable thought, because I want to get hired next time. Smile
My basic idea was to reduce the size of the original array, effectively reducing the number of possible subarrays.
There are about 10 rules you can formulate: e.g. a candidate subarray cannot start with a negative number or zero etc..
(You need to make proviso's for all negative arrays, which happen frequently if you do (-100, 10, k=30)
This is a dummy example:
Output:
arr = [-1,-2, 3, 4, 5,-6, 7, 8, 0,-9,-10, 11,-12] newarr = [ 12,-6, 15,-19, 11]
Unfortunately, every "if" comes with a penalty of about 0.1 secs in 100_000 runs. It is a trade-off, and I was not
able to write a "reducing" algorithm, that was fast enough to my taste. (Another interview question?)
So I ended up with a solution along the lines what was proposed above, yielding about 1.5 secs for 100_000 runs.
Paul
maxArr = [max(arr)]
subarr = 0
for number in arr:
    subarr += number
    if subarr > 0:
        maxArr.append(subarr)
    else:
        subarr = 0
maxarr = max(maxArr)
Gribouillis likes this post
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-07-2021, 08:39 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,272 Mar-05-2021, 04:08 PM
Last Post: SANJIB
  Find frequencies of an audio file at a specific time via librosa jberesford123__ 0 2,434 Oct-21-2020, 01:18 PM
Last Post: jberesford123__
  Find data using a period of time in SQLITE3 SmukasPlays 2 2,254 Jul-30-2020, 02:02 PM
Last Post: SmukasPlays
  Find if time is between start and end time mikke3141 3 2,347 Jan-03-2020, 08:48 PM
Last Post: mikke3141
  Find Maximum Flow for graph with infinite capacities Dav 6 4,403 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