using System;
class Program {
static void Main(string[] args)
{
int[] arr1
= { 100, 234, 416, 654, 412, 298, 820, 177 };
int[] arr2
= { 81, 24, 478, 905, 331, 138, 721, 565 };
int[] arr3 = { 1111, 2222, 3333, 4444, 5555 };
Console.WriteLine(
findLongestValidNumberLength(arr1));
Console.WriteLine(
findLongestValidNumberLength(arr2));
Console.WriteLine(
findLongestValidNumberLength(arr3));
Console.ReadKey();
}
public static int
findLongestValidNumberLength(int[] arr)
{
int maxValidLength = 0;
// Create a 2D array to store
// previous results
int[, ] dp = new int[10, 10];
// Iterate through the array in
// reverse order
for (int i = arr.Length - 1; i >= 0; --i) {
// Convert the number
// to a string
string numString = arr[i].ToString();
// Get the last digit
// of the number
int lastDigit
= numString[numString.Length - 1] - '0';
// Create a temporary array
// to store the results
int[] v = new int[10];
for (int d = 0; d < 10; ++d) {
// If there is a previously
// computed result for the
// last digit and the current
// digit, update the
// temporary array
if (dp[lastDigit, d] > 0) {
v[d] = numString.Length
+ dp[lastDigit, d];
}
}
// Update the temporary array
// to include the current
// number
v[lastDigit]
= Math.Max(v[lastDigit], numString.Length);
// Get the first digit
// of the number
int firstDigit = numString[0] - '0';
for (int d = 0; d < 10; ++d) {
// Update the 2D array with
// the computed results
dp[firstDigit, d]
= Math.Max(dp[firstDigit, d], v[d]);
}
// Update the maximum valid
// length if necessary
maxValidLength = Math.Max(
maxValidLength, dp[firstDigit, firstDigit]);
}
return maxValidLength;
}
}
// This code is contributed by Tapesh(tapeshdua420)