leetcode594

public class Solution {
    public int FindLHS(int[] nums) {
        Dictionary<int, int> dic = new Dictionary<int, int>();
            foreach (var num in nums)
            {
                if (!dic.ContainsKey(num))
                {
                    dic.Add(num, 1);
                }
                else
                {
                    dic[num]++;
                }
            }

            var list = dic.OrderBy(x => x.Key).ToList();
            if (list.Count == 1)
            {
                return 0;
            }
            else
            {
                var lastkey = 0;
                var lastLen = 0;
                var max = 0;
                for (int i = 0; i < list.Count; i++)
                {
                    if (i == 0)
                    {
                        lastkey = list[i].Key;
                        lastLen = list[i].Value;
                        continue;
                    }
                    else
                    {
                        var curKey = list[i].Key;
                        var curLen = list[i].Value;
                        if (curKey - lastkey == 1)
                        {
                            var totalLen = lastLen + curLen;
                            if (max < totalLen)
                            {
                                max = totalLen;
                            }
                        }
                        lastkey = curKey;
                        lastLen = curLen;
                    }
                }
                return max;
            }
    }
}

https://leetcode.com/problems/longest-harmonious-subsequence/#/description

原文地址:https://www.cnblogs.com/asenyang/p/6890493.html