Monday, February 3, 2014

Farthest Ascending Pair

Problem :
Given a sequence of integers A[n], find a pair of integers A[x]<A[y], such that y-x >= j-i and A[i]<A[j]

Solution:
In courtesy of JConstantine

 
class Solution
{
    public:
    std::vector<int> findLongestAscendingPair(const std::vector<int> &v) {
        std::vector<int> ret(2,0);
        int n = v.size();
        if(n == 0) return ret;
        std::vector<int> left(n,0);
        std::vector<int> right(n,0);
        left[0] = v[0];
        right[n-1] = v[n-1];
        for(int i=1; i<n; i++){
            left[i] = std::min(v[i], left[i-1]);
        }
        
        for(int i=n-2; i>=0; i--){
            right[i] = std::max(v[i], right[i+1]);
        }
        
        int i = 0, j = 0, distance = 0;
        while(i < n && j < n)
        {
            if(left[i] < right[j])
            {
                distance = std::max(j-i, distance);
                ret[0] = i;
                ret[1] = j;
                j = j + 1;
            }
            else
            {
                i = i+ 1;
            }
        }
        return ret;
    }
};

No comments:

Post a Comment