Ask Your Question
4

What is the Python code for finding the highest total of a subarray that has a length of k or less?

asked 2023-05-24 10:49:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2023-05-24 11:09:02 +0000

lakamha gravatar image

Here is Python code to find the highest total of a subarray that has a length of k or less:

def max_subarray_sum(arr, k):
    n = len(arr)
    if k > n:
        return "Invalid input"    # if k is larger than the array length, return an error message
    max_sum = -float("inf")   # initialize max_sum to negative infinity
    for i in range(n-k+1):
        curr_sum = sum(arr[i:i+k])   # calculate sum for current subarray of length k
        if curr_sum > max_sum:    # update max_sum if current sum is greater
            max_sum = curr_sum
    return max_sum

You can test this function with the following code snippet:

arr = [2, 4, 7, 6, 8, 9]
k = 3
print(max_subarray_sum(arr, k))   # output: 23

In this example, the highest total of any subarray with length 3 or less is 23, which is obtained by adding the last three elements of the input array [6, 8, 9].

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-24 10:49:00 +0000

Seen: 7 times

Last updated: May 24 '23