0
我写了这个方法来寻找数组中最长的增加子序列。我的问题是,在检查第二个for
循环中下一个索引是否更高之后,为什么我必须在之后使用else
块?如果我没有输出正确的结果。如果序列中的下一个较大,为什么不足以将currentSeq
增加1
?如果是false
,而不是继续进行控制流程,那么currentSeq仍留在1
?寻找最长增加子序列的问题
static void Main(string[] args)
{
int length = int.Parse(Console.ReadLine());
int[] nums = new int[length];
int currentSeq = 1;
int maxSeq = 1;
for (int i = 0; i < nums.Length; i++)
{
nums[i] = int.Parse(Console.ReadLine());
}
for (int i = 0; i < nums.Length - 1; i++)
{
if (nums[i] < nums[i + 1])
{
currentSeq++;
}
else
{
currentSeq = 1;
}
if (currentSeq > maxSeq)
{
maxSeq = currentSeq;
}
}
Console.WriteLine(maxSeq);
}
请考虑像“12123”这样的序列。在前两个数字后,你必须开始一个新的序列,但'currentSeq'是'2',而不是'1'。如果不将它重置为“1”,下面的序列长度将是“4”而不是“3”。 –