a c# dictionary solution


  • 0
    N
    public class Solution {
        public int FindLHS(int[] nums) {
            if(nums.Length==0) return 0;
            var dict = new Dictionary<int, int>();
            foreach(var n in nums){
                if(!dict.ContainsKey(n)) dict[n]=0;
                dict[n]++;
            }
            
            var max = 0;
            
            foreach(var d in dict){
                max = Math.Max(max, (dict.ContainsKey(d.Key-1)? d.Value+dict[d.Key-1]:0));
                max = Math.Max(max, (dict.ContainsKey(d.Key+1)? d.Value+ dict[d.Key+1]:0));
            }
            
            return max;
        }
    }
    

Log in to reply
 

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