Longest Contiguous Subsequence

Interview

Time limit1sMemory limit128 MB

Summary
Given two integer sequences, find the length of the longest run of consecutive elements that appears in both.
Level

Medium4 of 10

Topics
Dynamic programming, Array, Brute force, Implementation
Solved
No attempts yet

Problem

You are given two integer sequences S1S1 and S2S2. S1S1 has length L1L_1 (1≤L1≤1801 \le L_1 \le 180) and S2S2 has length L2L_2 (1≤L2≤1801 \le L_2 \le 180). Print the length of the longest contiguous subsequence of numbers common to both S1S1 and S2S2.

The elements of S1S1 are S11,S12,…,S1L1S1_1, S1_2, \dots, S1_{L_1} (−100≤S1i≤100-100 \le S1_i \le 100), and the elements of S2S2 are S21,S22,…,S2L2S2_1, S2_2, \dots, S2_{L_2} (−100≤S2i≤100-100 \le S2_i \le 100).

A contiguous subsequence is a consecutive run of numbers in the sequence. For example, the contiguous subsequences of 1 2 3 1 are: the empty sequence, 1, 1 2, 1 2 3, 1 2 3 1, 2, 2 3, 2 3 1, 3, 3 1, and a second occurrence of 1.

This is a typical problem that people solve early in their competitive programming career.

Input

  • Line 1: Two space-separated integers L1L_1 and L2L_2
  • Next L1L_1 lines: each line contains a single integer S1iS1_i
  • Next L2L_2 lines: each line contains a single integer S2iS2_i

Output

  • A single integer: the length of the longest contiguous subsequence common to S1S1 and S2S2

Hint

In the sample, the answer 77 corresponds to the common contiguous subsequence 1, 1, 1, 3, 2, 3, 3.

Examples1

  1. Example 1

    Input
    10 12
    1
    1
    1
    3
    2
    3
    3
    3
    4
    5
    1
    1
    1
    1
    3
    2
    3
    3
    4
    4
    5
    -8
    
    Expected output
    7