zoukankan      html  css  js  c++  java
  • 滑动窗口 sliding window

    From : https://www.educative.io/courses/grokking-the-coding-interview

    Maximum Sum Subarray of Size K (easy)

    1. problem statement

    Given an array of positive numbers and a positive number ‘k’, find the maximum sum of any contiguous subarray of size ‘k’.

     

    2. example

    Input: [2, 1, 5, 1, 3, 2], k=3 

    Output: 9

    Explanation: Subarray with maximum sum is [5, 1, 3].

     

    Input: [2, 3, 4, 1, 5], k=2 

    Output: 7

    Explanation: Subarray with maximum sum is [3, 4].

    3. brute force 穷举算法

    Calculate the sum of all ‘k’ sized subarrays of the given array, to find the subarray with the highest sum. We can start from every index of the given array and add the next ‘k’ elements to find the sum of the subarray.

    class MaxSumSubArrayOfSizeK {
      public static int findMaxSumSubArray(int k, int[] arr) {
        int maxSum = 0, windowSum;
        for (int i = 0; i <= arr.length - k; i++) {// for each index, we iterate the whole array
          windowSum = 0;
          for (int j = i; j < i + k; j++) {
            windowSum += arr[j];
          }// this for loop will calculate the windowSum that starts from index j.
          maxSum = Math.max(maxSum, windowSum);//finish one starting index, update our maxSum
        }
    
        return maxSum;
      }

    time complexity: O(N∗K), where ‘N’ is the total number of elements in the given array

    space complexity: O(1)

    4. sliding window 滑动窗口

    Main idea:

    • Consider each subarray as a Sliding Window of size ‘k’. To calculate the sum of the next subarray, we need to slide the window ahead by one element.
    • This approach will save us from re-calculating the sum of the overlapping part of the sliding window.

    Steps:

    1. Subtract the element going out of the sliding window i.e., subtract the first element of the window.
    2. Add the new element getting included in the sliding window i.e., the element coming right after the end of the window
     1 class MaxSumSubArrayOfSizeK {
     2   public static int findMaxSumSubArray(int k, int[] arr) {
     3     int windowSum = 0, maxSum = 0;
     4     int Start = 0;
     5     for (int End = 0; End < arr.length; End++) {
     6       windowSum += arr[End]; // add the next element
     7       // slide the window, we don't need to slide if we've not hit the required window size of 'k'
     8       if (End >= k - 1) {
     9         maxSum = Math.max(maxSum, windowSum);
    10         windowSum -= arr[Start]; // subtract the element going out
    11         Start++; // slide the window ahead
    12       }
    13     }
    14 
    15     return maxSum;
    16   }
    • Time: O(N)
    • Space: O(1) comstant space

    Smallest Subarray with a given sum (easy)

    1. problem statment

    Given an array of positive numbers and a positive number ‘S,’ find the length of the smallest contiguous subarray whose sum is greater than or equal to ‘S’. Return 0 if no such subarray exists.

    2. example

    Input: [2, 1, 5, 2, 3, 2], S=7 

    Output: 2

    Explanation: The smallest subarray with a sum great than or equal to '7' is [5, 2].

    3. Sliding window

    This problem follows the Sliding Window pattern, but the sliding window size is not fixed

    1. First, we will add-up elements from the beginning of the array until their sum becomes greater than or equal to ‘S.’
    2. These elements will constitute our sliding window. We are asked to find the smallest such window having a sum greater than or equal to ‘S.’ We will remember the length of this window as the smallest window so far.
    3. After this, we will keep adding one element in the sliding window (i.e., slide the window ahead) in a stepwise fashion.
    4. In each step, we will also try to shrink the window from the beginning. We will shrink the window until the window’s sum is smaller than ‘S’ again. This is needed as we intend to find the smallest window. This shrinking will also happen in multiple steps; in each step, we will do two things:
      • Check if the current window length is the smallest so far, and if so, remember its length.
      • Subtract the first element of the window from the running sum to shrink the sliding window.
         1 class MinSizeSubArraySum {
         2   public static int findMinSubArray(int S, int[] arr) {
         3     int windowSum = 0, minLength = Integer.MAX_VALUE;
         4     int Start = 0;
         5     for (int End = 0; End < arr.length; End++) {
         6       windowSum += arr[End]; // add the next element
         7       // shrink the window as small as possible until the 'windowSum' is smaller than 'S'
         8       while (windowSum >= S) {
         9         minLength = Math.min(minLength, End - Start + 1);
        10         windowSum -= arr[Start]; // subtract the element going out
        11         Start++; // slide the window ahead
        12       }
        13     }
        14 
        15     return minLength == Integer.MAX_VALUE ? 0 : minLength;
        16   }
        • Time: O(N)
        • Space: O(1) comstant space
  • 相关阅读:
    MongoDb
    js暴露内部方法属性等
    JS闭包
    k8s设计模式
    scrum
    死锁
    Linux下安装php 扩展fileinfo
    linux中whereis、which、find、location的区别和用法
    Linux 命令学习记录
    windows 下 redis 的安装及使用
  • 原文地址:https://www.cnblogs.com/LilyLiya/p/14222747.html
Copyright © 2011-2022 走看看