package cn.exploring.engine.server.db.util;

import java.util.ArrayList;
import java.util.List;

public class Util {
    public static void main(String[] args) {
        List<Integer> list = new ArrayList<>();
        list.add(100);
        list.add(1);
        list.add(3);
        list.add(4);
        list.add(5);
        list.add(2);
        list.add(6);
        list.add(9);

        System.out.println(longestConsecutive(list));
    }


    /**
     * 最长连接子序列长度
     * 哈希表+动态规划
     */
    public static int longestConsecutive(List<Integer> list) {
        int result = 0;
        for (int num : list) {
            //若num-1不在哈希表中，说明num是连续序列的第一个元素，由此元素开始遍历
            if (!list.contains(num - 1)) {
                int curNum = num;
                int curLen = 1;
                while (list.contains(curNum + 1)) {
                    curNum++;
                    curLen++;
                }
                result = curLen > result ? curLen : result;
            }
        }

        return result;
    }
}
