The Problem:
Given an array of integers
L
find the largest sum of a consecutive subarray of sizek
or less.Constraints:
2 <= len(L) <= 10000
3 <= k <= len(L)
each element in the array will have an absolute value no more than
200
there will be at least one positive integer in the array
L
Samples:
L=[-200, 91, 82, 43]
,k=3
, the result should be216
L=[41, 90, -62, -16, 25, -61, -33, -32, -33]
,k=5
, the result should be131
The Implementation:
Initially, I started with brute-forcing the problem, probing all sizes of the sliding window starting from k
to 1
. This immediately got me into "time limit exceeded" situation.
The idea implemented below is based on picking out only positive integers initially. For every positive integer, we are looking if the following integers in a window are contributing to the current sum or not, cutting off situations when current sum drops below zero:
def maximum_consecutive_subarray(L, k):
global_max = 0
for index in range(len(L) - 1, -1, -1):
if L[index] < 0: # skipping all negative values
continue
sliding_index = index
positive_count = positive_sum = 0
while sliding_index >= 0 and positive_count < k:
if L[sliding_index] >= 0:
positive_count += 1
positive_sum += L[sliding_index]
global_max = max(global_max, positive_sum)
else:
negative_count = 1
negative_sum = L[sliding_index]
while sliding_index - 1 >= 0 > L[sliding_index - 1]: # iterating over all consecutive negative values
negative_count += 1
negative_sum += L[sliding_index - 1]
sliding_index -= 1
if positive_count + negative_count == k: # break if sliding window size limit reached
break
if positive_sum + negative_sum > 0: # if we still contribute to the maximum value
positive_count += negative_count
positive_sum += negative_sum
else:
break # exit this window if nothing was to contribute
sliding_index -= 1
return global_max
I would like to know if we can further improve the solution time complexity wise and would appreciate any other feedback.
k
- this is though, as it appears to be, a much simpler problem than the one wherek
is variable..thanks. \$\endgroup\$