Home > database >  How to find the max of continuous subarray of size k
How to find the max of continuous subarray of size k

Time:09-18

l = [2,1,5,1,3,2]

subarrays are [2,1,5] [1,5,1],[5,1,3],[1,3,2]

output is [5 ,1 , 3] which is 9

My code is


def maxcosu(arr,k):
    maxtotal = 0
    for i in range(len(arr)-k):
        total = 0
        for j in range(i, i k):
            total = total   arr[j]
        maxtotal = max(maxtotal, total)
    return maxtotal
maxcosu([2,1,5,1,3,2] , 3)

But for [1,1,1,8,8,8] My Expected out is 24, but i am getting 17

I have gone through link To find max continuous subarray sum of size M

the answer by zeeshan12396 is wrong for test case

CodePudding user response:

Talking about your solution, I guess you should have passed len(arr)-k 1 instead of len(arr)-k to range builtin.

Here is one-liner solution using List-Comprehension to get continuous sub-array of length k for maximum sum:

>>> max((l[i:i k] for i in range(len(l)-k 1)), key=sum)
[8, 8, 8]

And to get the maximum sum:

>>> max((sum(l[i:i k]) for i in range(len(l)-k 1)))
24

CodePudding user response:

import math

arr =[1,1,1,8,8,8]
k = 3

list = []
iterations = len(arr)   1 - k


for i in range(iterations):
    list.append(arr[0 i:3 i])
print(list)

suml = []

for l in list:
    suml.append(math.fsum(l))
print(suml)

max_val = max(suml)
print(max_val)

max_idx = suml.index(max_val)
print(max_idx)

correct_arr = list[max_idx]
print(correct_arr)

I think this is what you are looking for?

CodePudding user response:

Following your logic, I have got:

def maxcosu(arr,k):
    sub_arr_sum = []
    for i in range(len(arr)-k 1):
        sub_arr_sum.append(sum(arr[i:i k]))
    return max(sub_arr_sum)
  • Related