滑动窗口的应用

通过一个简单的题目说一下滑动窗口

 

滑动窗口的应用_第1张图片

 1 public class SlidWindow {
 2     public static int slid(int [] arr,int n,int k){
 3         int maxSum = Integer.MIN_VALUE;
 4         //需要滑动的次数
 5         for (int i = 0; i < n - k + 1 ; i++) {
 6             int currentSum = 0;
 7             //每个子窗口的值
 8             for (int j = 0; j < k ; j++) {
 9                 currentSum = currentSum + arr[i + j];
10             }
11 
12             maxSum = Math.max(currentSum,maxSum);
13         }
14         return maxSum;
15     }
16 
17     public static void main(String[] args) {
18         int [] arr = {5,2,-1,0,3};
19         int k = 3;
20         int n = arr.length;
21         System.out.println(slid(arr,n,k));
22     }
23 }

你可能感兴趣的:(滑动窗口的应用)