c语言求数组最长升序子序列,算法:最大升序子序列长度

刚开始写,如有错误还望各位看官指出。若有描述不清,也请诸位提点。

导读

通过动态规划使用C语言实现求数组中最大升序(或降序)子序列长度问题。

原题

Longest Increasing Subsequence

Given an unsorted array of integers, find the length of longest increasing subsequence.

For example,

Given[10, 9, 2, 5, 3, 7, 101, 18],

The longest increasing subsequence is[2, 3, 7, 101], therefore the length is4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.

Your algorithm should run in O(n2) complexity.

Follow up:Could you improve it to O(nlogn) time complexity?

Credits:

Special thanks to@pbrotherfor adding this problem and creating all test cases.

Subscribeto see which companies asked this question.

翻译:

给出一个无序的整形数组,找出它的最大升序子序列。

举个栗子,

示例数组 arr[] = {10, 9, 2, 5, 3, 7, 101, 18},

数组arr的最长升序子序列是 {2, 3, 7, 101},因此长度是4。

请注意,可能有一个以上的LIS(最长上升子序列)的组合,只需要返回长度就好。

时间复杂度O(n²)前提下实现。

进阶:时间复杂度O(nlogn)前提下实现。

以下不译。

正文

以下为两种时间复杂度的C语言解法,已将log相关代码注释掉了,并粘上分步log,并简要概述思路,共同学习进步。

O(n²)

思路:

定义一个数组lis,记录以目标序列nums[0]开头,以每个元素结尾的子串的最大升序子串长度。

取出li

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
解一个数组最大连续子序列和是一个常见的问题,可以使用动态规划的思想来解决。具体算法步骤如下: 1. 定义一个变量 max_sum 表示最大连续子序列和,初始值为数组第一个元素。 2. 定义一个变量 current_sum 表示当前连续子序列和,初始值为数组第一个元素。 3. 从数组第二个元素开始遍历,如果 current_sum 加上当前元素的值大于当前元素的值,则将 current_sum 更新为 current_sum 加上当前元素的值,否则将 current_sum 更新为当前元素的值。 4. 每次更新 current_sum 之后,将 current_sum 和 max_sum 中的较大值赋给 max_sum。 5. 遍历完成后,max_sum 中存储的即为最大连续子序列和。 下面是 C 语言代码实现: ```c int max_subarray_sum(int arr[], int n) { int max_sum = arr[0], current_sum = arr[0]; for (int i = 1; i < n; i++) { current_sum = current_sum + arr[i] > arr[i] ? current_sum + arr[i] : arr[i]; max_sum = current_sum > max_sum ? current_sum : max_sum; } return max_sum; } ``` 在该代码中,max_subarray_sum() 函数接收一个待处理的数组数组长度,首先定义 max_sum 和 current_sum 两个变量的初始值为数组的第一个元素。然后从数组的第二个元素开始遍历,如果 current_sum 加上当前元素的值大于当前元素的值,则将 current_sum 更新为 current_sum 加上当前元素的值,否则将 current_sum 更新为当前元素的值。每次更新 current_sum 之后,将 current_sum 和 max_sum 中的较大值赋给 max_sum。最后返回 max_sum 即为最大连续子序列和。 该算法的时间复杂度为 O(n),空间复杂度为 O(1)。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值