DEV Community

Prashant Mishra
Prashant Mishra

Posted on

Pattern: Sliding window (fixed window)

Problems that involves operations on contiguous range of substring/subarray
eg. Maximum sum subarray of size k (Fixed window of size K)

class Solution {
    public int maxSubarraySum(int[] arr, int k) {
        // Code here
        int left  =0;
        int right  =0;
        int sum = 0;
        int max = Integer.MIN_VALUE;
        while(right<arr.length){
            if(right-left+1<k){
                sum+=arr[right];
                right++;
            }
            else{
                sum+=arr[right];
                max = Math.max(max, sum);
                sum = sum-arr[left];
                left++;
                right++;
            }
        }
        return  max;
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)