C++ One-pass with at most Two Subtractions


  • 0
    G
    class Solution {
    public:
        int maxDistance(vector<vector<int>>& arrays) {
            
            auto max1 = INT_MIN;
            auto max2 = INT_MIN;
            auto max1Index = -1;
            
            auto min1 = INT_MAX;
            auto min2 = INT_MAX;
            auto min1Index = -1;
            
            for(auto i = 0 ; i < arrays.size(); i++){
                
                // update the max1/max2
                if(max1 < arrays[i].back()){
                    max2 = max1;
                    max1 = arrays[i].back();
                    max1Index = i;
                }else if(max2 < arrays[i].back()){
                    max2 = arrays[i].back();
                }
            
                // update the min1/min2
                if(arrays[i].front() < min1){
                    min2 = min1;
                    min1 = arrays[i].front();
                    min1Index = i;
                }else if(arrays[i].front() < min2){
                    min2 = arrays[i].front();
                }
            }
            
            return (max1Index != min1Index) ? max1-min1 : std::max(max1-min2, max2-min1);
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.