2

Is there a way to find in O(N) complexity, a maximal contiguous subarray with at most K elements.

Or there isn't such a possibility.

for example:

A = [4, -2, 6, 4, -2, 6]

K = 3

because 6 and 4 in the middle are equal to 10, the function should return 10.

P.S. with O(NK) it's easy, the question is whether it is possible in O(N) Here is an algorithm that solves in O(NK) time:

def maxContiguousFragment(arr):
    b = max(arr)
    s = 0
    for i in arr:
        s = max(s + i, i)
        b = max(s, b)
    return b

def max_K_Subarray(arr,k):
    return max(maxContiguousFragment(
            arr[i:i+k] for i in range(len(arr)-k)))
Avraham
  • 61
  • 1
  • 4

0 Answers0