This problem is fucking killing me


#1

I’m using two pointer here with 3 conditions.

  1. If in range increase pointer
  2. If less than upper bound, increase right end of window.
  3. If greater than upper bound, decrease the left end of window.

Finally check until left end equals right end, continuously decreasing window

    int start=0;
    int end=0;
    int sum=A[start];
    int count=0;
    
    while(1){
        if(end==A.size()-1)break;
        
        if(sum>=B && sum<=C){
            count++;
            end++;
            sum+=A[end];
        }
        else if(sum<=C){
            end++;
            sum+=A[end];
        }
        else if(sum>C){
            sum-=A[start];
            start++;
            if(start>end){
                end++;
                sum+=A[end];
            }
        }
    }
    
    while(start!=A.size()){
        if(sum>=B && sum<=C){
            count++;
        }
        sum-=A[start];
        start++;
    }
    
    return count;

Why is this code giving less than half of the required answer
Test case: { 80, 97, 78, 45, 23, 38, 38, 93, 83, 16, 91, 69, 18, 82, 60, 50, 61, 70, 15, 6, 52, 90};
My Output: 24
Actual Output: 58


#2

actually you missing a lot of subarrays b/w those pointers


#3

Two pointer algorithm works on sorted array.


#4

Bro see my two pointer solution using sliding window concept

int Solution::numRange(vector<int> &A, int B, int C) {
    int ans = 0;
    int n = A.size();
    if(n==1){
        if(A[0]>=B&&A[0]<=C)return 1;
        return 0;
    }
    int j = 0;int sum = 0;
    int i =0;
        while(i<n){
           // cout<<sum<<" "<<ans<<' ';
           // cout<<i<<' '<<j  <<'\n';
			if(sum>C){sum=0;i++;j = i;}
            else {sum+=A[j];j++;}
            if(sum<=C&&sum>=B)ans++;

            if(j==n){sum=0;i++;j=i;}

        }
    return ans;
    
}