Easy C++ with comments using unordered_map : beats 95%


  • 0
    A
    class Solution {
    public:
        int findLHS(vector<int>& nums) {
            unordered_map<int,int> hash;
            if(nums.size()==0) return 0;
            
            //store all the integer frequencies
            for(int i=0;i<nums.size();i++)
                hash[nums[i]]++;
            
            //stores the max subarray count where the difference between the max and min values is 1
            int maxSum=0;
            
            for(auto const i: hash){
                //find elem with key with difference of 1
                int k = i.first;
                if(hash.find(k-1)!=hash.end())
                    maxSum = max(maxSum, i.second + hash[k-1]);
            }        
            return maxSum;
        }
    };
    

Log in to reply
 

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