Search code examples
pythonpython-3.xpython-2.7python-3.8

To find max continuous subarray sum of size M


I am new to the competitive programming. I am finding trouble in doing the following problem.

The question is that you have given an array or list. And a number M, now you hav to find the continuous subarray of size M having the largest sum.

For example if list is 4,6,10,8,2,1 and M=3 then largest sum window will be 6,8,10 that is sum equal 24 . So answer will be 24

Can anyone help me regarding this question?


Solution

  • You can edit the list and remove the largest number successively:

    list = [4,6,10,8,2,1]
    M = 3
    result = 0
    # to get unique elements
    new_list = set(list)
    
    for i in range(M):
       result += max(new_list)
       # removing the largest element from new_list
       new_list.remove(max(new_list))
    
    print(result)