Sliding Window pattern in DSA questions
1. Maximum Sum Subarray of Size K (easy)
Questions Details
Given an array of positive numbers and a positive number ‘k’, find the maximum sum of any contiguous subarray of size ‘k’.
</br> Example 1: </br> Input: [2, 1, 5, 1, 3, 2], k=3 </br> Output: 9 Explanation: Subarray with maximum sum is [5, 1, 3]. * Example 2: Input: [2, 3, 4, 1, 5], k=2 Output: 7 Explanation: Subarray with maximum sum is [3, 4].Implementation
-
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
def max_sub_array_of_size_k(k, arr): max_sum , window_sum = 0, 0 window_start = 0 for window_end in range(len(arr)): window_sum += arr[window_end] # add the next element # slide the window, we don't need to slide if we've not hit the required window size of 'k' if window_end >= k-1: max_sum = max(max_sum, window_sum) window_sum -= arr[window_start] # subtract the element going out window_start += 1 # slide the window ahead return max_sum def main(): print("Maximum sum of a subarray of size K: " + str(max_sub_array_of_size_k(3, [2, 1, 5, 1, 3, 2]))) print("Maximum sum of a subarray of size K: " + str(max_sub_array_of_size_k(2, [2, 3, 4, 1, 5]))) main()
-
1
console.log('hello');
-
1
pputs 'hello'
A collapsible section with markdown
Click to expand!
## Heading 1. A numbered 2. list * With some * Sub bullets- Assert: Type(iterator) is Object.
- Assert: completion is a Completion Record.
- Let hasReturn be HasProperty(iterator,
"return"
). - ReturnIfAbrupt(hasReturn).
- If hasReturn is
true , then- Let innerResult be Invoke(iterator,
"return"
, ( )). - If completion.[[type]] is not
throw and innerResult.[[type]] isthrow , then- Return innerResult.
- Let innerResult be Invoke(iterator,
- If hasReturn is
- Return completion.