Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 最长的子序列,使得邻接之间的差为一_Arrays_Algorithm_Dynamic Programming - Fatal编程技术网

Arrays 最长的子序列,使得邻接之间的差为一

Arrays 最长的子序列,使得邻接之间的差为一,arrays,algorithm,dynamic-programming,Arrays,Algorithm,Dynamic Programming,代码: Geeksforgeks对某些输入给出了错误的答案。这个算法正确吗?或者我遗漏了任何角点情况吗?您发布的代码似乎解决了一个不同的问题-找到元素相差+1或-1的最长子数组的长度。也就是说,此代码只查找具有此属性的最长连续元素范围,而您正在查找具有此属性的最大元素组,即使它们不是连续的 作为解决问题的提示:从左到右扫描阵列。每当您看到一个元素时,您都需要一种快速的方法来回顾前面的数组元素,以确定您的数字是否可以扩展任何现有的序列。因此,维护一个哈希表,存储以前看到的数字以及以这些数字结尾的最

代码:


Geeksforgeks对某些输入给出了错误的答案。这个算法正确吗?或者我遗漏了任何角点情况吗?

您发布的代码似乎解决了一个不同的问题-找到元素相差+1或-1的最长子数组的长度。也就是说,此代码只查找具有此属性的最长连续元素范围,而您正在查找具有此属性的最大元素组,即使它们不是连续的


作为解决问题的提示:从左到右扫描阵列。每当您看到一个元素时,您都需要一种快速的方法来回顾前面的数组元素,以确定您的数字是否可以扩展任何现有的序列。因此,维护一个哈希表,存储以前看到的数字以及以这些数字结尾的最长子序列的长度,并考虑在看到新数字后如何更新该表。

如果我们对数组进行排序,然后运行子数组算法,也应计算差值为1的最长子序列,但这种方法行不通。为什么?考虑数组[10, 1, 9,2, 8, 3,7, 4, 6,5 ]。这里,差为1的最长子序列是10、9、8、7、6、5。但是,如果对其进行排序,则会得到[1,2,3,4,5,6,7,8,9,10],并且会错误地报告更长的序列。
    Input:
    10 9 4 5 4 8 6
    Output:
    3

NOTE: For arrays with only 1 element or if no adjacent elements in array have difference 1, print 1 as output
int longestSubSequence(int arr[],int n) {
    int local_length=1;
    int max_length=1;
    for(int i=0;i<n-1;i++) {
       if(abs(arr[i]-arr[i+1])==1) {
           local_length++;
       } else {
           max_length=max_length>local_length?max_length:local_length;
        local_length=1;
           }
        }
max_length=max_length>local_length?max_length:local_length;
        return max_length;
    }

Algorithm:
1. Maintain 2 different length: local_length and max_length initialized to 1.
2. For every subsequence whose difference is 1, local_length is increased by 1.
3. When difference between adjacent elements is not 1, max_length is updated.
4. If subsequence forms at last, so max_length is updated outside the array.