O(n) C++ solution using Map. Any improvements?


  • 0
    S

    class Solution {
    public:
    int findLHS(vector<int>& nums) {
    if(nums.size()<2) return 0;
    int max_count =0;

        map<int, int> mp;
        for(int i=0; i<nums.size(); i++) {
            mp[nums[i]]++;
        }
        int count;
        for(auto num:nums) {
            count = mp[num];
            mp[num]--;
            int less=mp[num-1];
            int more=mp[num+1];
            if(less==0 && more==0) continue;
            max_count = max(count+more, max_count);
            max_count = max(max_count, count+less);
        }
    
        
        return max_count;
    }
    

    };


Log in to reply
 

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