...

/

Solution: Maximum Sum Sublist of Size K

Solution: Maximum Sum Sublist of Size K

This review discusses the solution of the "maximum sum sublist of size k" challenge in detail.

Solution: 1

A naive solution to this problem is to find the sum of all possible contiguous sublists of size k, find the maximum of those sums, and return that sum. This approach can easily be implemented using two for loops.

def max_sub_list_of_size_k(lst, k):
"""
Finds a maximum sum of a sub-list of given window size k
:param lst: List of integers
:param k: Window size of the list
:return: Returns the maximum sum of a sub-list of given window size k
"""
max_sum = 0
window_sum = 0
for i in range(len(lst) - k + 1): # Loop runs (List Size - k +1) times
window_sum = 0
for j in range(i, i + k): # Loop in a window
window_sum += lst[j]
max_sum = max(max_sum, window_sum) # Updating the max sum
return max_sum
# Driver code to test above function
if __name__ == '__main__':
print("Maximum sum of a sub-list of size K: " + str(max_sub_list_of_size_k([2, 1, 5, 1, 3, 2], 3)))
print("Maximum sum of a sub-list of size K: " + str(max_sub_list_of_size_k([2, 3, 4, 1, 5], 2)))

Explanation

Line 11: Outer for loop runs for the ...

Access this course and 1400+ top-rated courses and projects.