已知序列a1,a2,…,an,试设计一算法,从中找出一子序列ai1 <= ai2 <= … <= aik,使k达到最大。
C# codes as below,
class Program
{
static void Main(string[] args)
{
GetMaxString(new int[]{1,2,3,2,3,1});
Console.ReadKey();
}
static void GetMaxString(int[] array)
{
int startIndex = 0;
int maxLength = 1;
int currentLength = 1;
for (int i = 0; i < array.Length-1; i++)
{
if (array[i] <= array[i + 1])
{
currentLength++;
if (currentLength > maxLength)
{
maxLength = currentLength;
startIndex = i - maxLength + 2;
}
}
else
{
currentLength = 1;
}
}
for (int i = startIndex; i < startIndex + maxLength; i++)
{
Console.Write("{0} ", array[i]);
}
Console.WriteLine();
}
}
Output:
1 2 3