Home Sliding Window Patterns
Post
Cancel

Sliding Window Patterns

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
  1. Assert: Type(iterator) is Object.
  2. Assert: completion is a Completion Record.
  3. Let hasReturn be HasProperty(iterator, "return").
  4. ReturnIfAbrupt(hasReturn).
    1. If hasReturn is true, then
      1. Let innerResult be Invoke(iterator, "return", ( )).
      2. If completion.[[type]] is not throw and innerResult.[[type]] is throw, then
        1. Return innerResult.
  5. Return completion.
This post is licensed under CC BY 4.0 by the author.