交错序列, 美团笔试题

动态规划

import java.util.*;
public class Main {
    public static void main(String[] args) { 
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int[] a = new int[n];
        for(int i=0; i < n; i++) a[i] = sc.nextInt();
        int[] f = new int[n];
        f[0] = 1;
        for(int i=1; i < n; i++) {
            if(a[i] == a[i-1]) 
                f[i] = f[i-1];
            else
                f[i] = f[i-1] + 1;
        }
        int res = 0; 
        for(int i=0; i < n; i++) 
            res = Math.max(res, f[i]);
        System.out.println(res);
    }
}
/*
f[i] 表示以a[i]结尾最长交错序列的长度
if a[i] == a[i-1] f[i] = f[i-1]
else f[i] = f[i-1] + 1
*/

猜你喜欢

转载自www.cnblogs.com/lixyuan/p/13205033.html