How to find the max of continuous subarray of size k
Question:
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 output is 24, but I am getting 17.
I have gone through this link and the answer by zeeshan12396 is wrong for test case
Answers:
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
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:k+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?
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)
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 output is 24, but I am getting 17.
I have gone through this link and the answer by zeeshan12396 is wrong for test case
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
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:k+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?
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)