Two-pointer and sliding window patterns
Pattern 1: Constant window(Like window = 4 or some Integer value)
For example given an array of (-ve and ve) integers find the max sum for the contiguous window of size k.
Pattern 2:(Variable window size) Largest subarray/substring with Pattern 3: No of subarray/substring where This problem can be solved using Pattern 2 This can be broken down to Pattern 4: Find the shortest/minimum window Different approaches for pattern 2: Better approach using the two pointers and the sliding window Optimal approach: An optimal approach will be to only shrink the left as long as the subarray length is more than the maxLen when the subarray is not satisfying the condition (
This is very difficult to solve because it becomes difficult when to expand (right ) or when to shrink(left ).
For solving problems like finding the number of substrings where sum =k.
Example: Largest subarray with sum
public class Sample{
public static void main(String args[]){
n = 10;
int arr[] = new int[n];
//Brute force approach for finding the longest subarray with sum k) break; /// optimization if the sum is greater than the k, what is the point in going forward?
}
}
//O(n n) in the worst case r will move from 0 to n and in the worst case left will move from 0 0 n as well so 2n
int left = 0;
int right =0;
int sum = 0;
int maxLen = 0;
while(right
We know that if we find the subarray we store its length in maxLen, but while adding arr[right] if the sum becomes more than the k then currently we are shrinking left by doing sum = sum-arr[left] and doing left .
We know that the current Max length is maxLen, if we keep on shrinking the left index we might get another subarray satisfying the condition ( maxLen, then only maxLen will be updated. int right =0;
int sum = 0;
int maxLen = 0;
while(right
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3