Max Sum Subarray of size K Python
PROGRAM TO FIND MAXIMUM SUM OF A SUBARRAY OF SIZE K
OUTPUT:
24
def maxSum(arr, n, k): # k must be greater if (n < k): print("Invalid") return -1 # Compute sum of first # window of size k res = 0 for i in range(k): res += arr[i] # Compute sums of remaining windows by # removing first element of previous # window and adding last element of # current window. curr_sum = res for i in range(k, n): curr_sum += arr[i] - arr[i-k] res = max(res, curr_sum) return res # Driver code arr = [1, 4, 2, 10, 2, 3, 1, 0, 20] k = 4n = len(arr) print(maxSum(arr, n, k))
24
Comments
Post a Comment