Sliding Window
Sliding Window
not satisfy then increment left abd try to maintain the window.
Template for all problem:
int s=0;
int e=0;
int cnt=0;
int ans=0;
for(;e<nums.size();e++){
calculation to be done
Calculation
return ans;
}
Types of problem:
Basic:
Longest Subarray of 1's After Deleting One Element
1493:Given a binary array nums, you should delete one element from it.
Return the size of the longest non-empty subarray containing only 1's in the resulting array.
Return 0 if there is no such subarray.
class Solution {
public:
int longestSubarray(vector<int>& nums) {
int s=0;
int e=0;
int cnt=0;
int ans=0;
for( e=0;e<nums.size();e++){
if(nums[e]==0){
cnt++;
}
for(;cnt>1;s++){
if(nums[s]==0){
cnt--;
}
}
ans=max(ans,e-s+1);
}
return ans-1;
}
};
Using hashmap:
class Solution {
public:
int numberOfSubstrings(string s) {
int si=0,e=0,ans=0;
map<char,int>mp;
for(;e<s.size();e++){
mp[s[e]]++;
for(;mp['a']>=1&&mp['b']>=1&&mp['c']>=1;si++){
ans+=s.size()-e;
mp[s[si]]--;
}
return ans;
}
};
One with prefix sum:
Given an array of positive integers nums and a positive integer target, return the minimal length
of a
Subarray whose sum is greater than or equal to target. If there is no such subarray, return 0
instead.
class Solution {
public:
int minSubArrayLen(int target, vector<int>& nums) {
int s=0;
int e=0;
int ans=INT_MAX;
bool flag=false;
int sum=0;
for(;e<nums.size();e++){
sum+=nums[e];
for(;sum>=target;s++){
flag=true;
ans=min(ans,e-s+1);
sum-=nums[s];
}
}
if(!flag){
return 0;
}
return ans;
}
};
A different varient when we find all the possible subarray from given goal to 0 and
minus that with all total subarray from goal-1 to 0 so we can find the subarray for
given goal exact.
930.Given a binary array nums and an integer goal, return the number of non-empty subarrays with
a sum goal.
A subarray is a contiguous part of the array.
Input: nums = [1,0,1,0,1], goal = 2
Output: 4
class Solution {
private:
int array(vector<int>& nums, int goal){
int s=0,e=0;
int sum=0;
int ans=0;
for(;e<nums.size();e++){
sum+=nums[e];
for(;sum>goal&&s<=e;s++){
sum=sum-nums[s];
}
ans+=e-s+1;
}
return ans;
}
public:
int numSubarraysWithSum(vector<int>& nums, int goal) {
return array(nums,goal)-array(nums,goal-1);
}
};