如何使用 C# 从数字数组中找到最长连续递增子序列的长度?
csharpserver side programmingprogramming更新于 2025/4/18 8:37:17
LongestIncreaingSubsequence 返回数组中连续子序列的整数。该方法有一个 for 循环,它会迭代并跟踪数字。最终结果将计算出最大值。时间复杂度为 O(N),因为每个元素都被访问一次,空间复杂度为 O(1),因为我们没有使用任何存储空间。
时间复杂度 − O(N)
空间复杂度 − O(1)
示例 − {2,4,6,5,8>
输出 − 3
示例
public class Arrays{
public int longestIncreaingSubsequence(int[] nums){
if (nums == null || nums.Length == 0){
return -1;
}
int res = 0, count = 0;
for (int i = 0; i < nums.Count(); i++){
if (i == 0 || nums[i] > nums[i - 1]){
count++;
res = Math.Max(res, count);
}
else{
count = 1;
}
}
return res;
}
}
static void Main(string[] args){
int[] nums = { 1, 3, 5, 4, 7 };
Console.WriteLine(s.longestIncreaingSubsequence(nums));
}
输出
3

