Short optimized C# Solution [O(N)]


  • 0
    R
        public int FindLHS(int[] nums) {
            var sDic = new Dictionary<int,int>();
            int ans = 0;
            foreach(var num in nums)
                sDic[num] = sDic.ContainsKey(num) ? sDic[num]+1 : 1;
            
            foreach(KeyValuePair<int,int> kv in sDic)
                if(sDic.ContainsKey(kv.Key-1))
                    ans = Math.Max(ans, kv.Value+sDic[kv.Key-1]);
            
            return ans;
            
        }
    

Log in to reply
 

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