Set approach NO TLE


#1
 int Solution::solve(vector<int> &A) {
    int length = A.size();
    
    // Right F Arr 
    vector<int> rfA(length);
    rfA[length-1]=A[length-1];
    for(int nk=length-2;nk>=0;nk--)
    {
        rfA[nk]=max(rfA[nk+1],A[nk]);
    }
    
    int sum=INT_MIN;
    set<int> myset;
    for(int i=1; i<length;i++)
    {
        myset.insert(A[i-1]);
        if(A[i]<rfA[i])
        {
            int ans;
            auto it = myset.lower_bound(A[i]);
            if( it == myset.begin())
            {
                ans = INT_MIN;
            }  
            else{
                --it;
                ans = *it;
            }
            sum = max(sum,ans+A[i]+rfA[i]);
        }
    }
    return sum;
}

I don’t know why but instead of writing a function for finding prev elem of lowerbound, writing it directly can pass the TLE. I would like to know the reason as well.