Given an array of integers, take any two non-intersecting subarrays, A1 and A2. A subarray could be empty too. we have to return the max(sum(A1,A2)). The return value is the maximum possible sum of two subarrays of the given array.
My Thoughts:
Find the max sum subarray. This will give two new subarrays, the left of it and the right of it. Find the max sum subarray left and right and choose the optimal one. I am not sure if this will yield the max answer.
Any ideas or approach?
CodePudding user response:
Find the max subarray ending at index i
going left and find the max subarray ending at index i
going right. Then for each candidate, update the best result with the larger of the current best or max_subarray_sum_on_the_left[i] max_subarray_sum_on_the_right[i 1]
.
In case it was unclear -- when performing Kadane's algorithm for each direction, save for each index the best seen from that direction. This leads to an O(n)
overall solution.
CodePudding user response:
- Create array
left[]
such thatleft[i] = max subarray sum ending at index i
(takesO(N)
time) - Create array
right[]
such thatright[i] = max subarray sum starting at index i
(takesO(N)
time) - Iterate over the arrays and keep track of the max value visited such that
left[i] = max possible sum over all subarrays ending at i
andright[i] = max possible sum over all subarrays starting at i
. (takesO(N)
time) - Loop
i
from1
toN-1
, wherei
is the index about which we'll "partition" our array and choose non-intersecting subarrays. For a giveni
, the answer will beleft[i] right[i]
The solution has O(N)
space and time complexity.