Priyanka and Toys

  • + 1 comment

    C++ implementation : Intution:- First sort the array and then check with the first element(threshold) if the element is <= threshold+4 , keep going and when it fails the condition increment the answer.

    int toys(vector<int> w) {
        sort(w.begin(),w.end());
        int ans=1;
        int n=w.size();
        int j=0;
    
            int threshold = w[0]+4;
            
            while(j < n){
                if(w[j] <= threshold){
                    j++;
                }
                else {
                    ans++;
                    threshold = w[j]+4;
                    j++;
                    } 
                }
            
        return ans;
    }