当前位置:网站首页>Leetcode 1218. Longest definite difference subsequence (providing an idea)

Leetcode 1218. Longest definite difference subsequence (providing an idea)

2022-06-23 18:25:00 I'm not xiaohaiwa~~~~

Give you an array of integers arr And an integer difference, Please find out and return to arr The length of the longest isochromatic subsequence in , The difference between adjacent elements in this subsequence is equal to difference .

Subsequence It means that without changing the order of the other elements , Remove from... By deleting some elements or not deleting any elements arr Derived sequence .

Example 1:

 Input :arr = [1,2,3,4], difference = 1
 Output :4
 explain : The longest isochromatic subsequence is  [1,2,3,4].

Example 2:

 Input :arr = [1,3,5,7], difference = 1
 Output :1
 explain : The longest arithmetic subsequence is any single element .

Example 3:

 Input :arr = [1,5,7,8,5,3,4,2,1], difference = -2
 Output :4
 explain : The longest isochromatic subsequence is  [7,5,3,1].
 

Tips :

  • 1 <= arr.length <= 10^5
  • -104 <= arr[i], difference <= 10^4

Code:

class Solution {
    
public:
    int longestSubsequence(vector<int>& arr, int difference) {
    
        int maxlen=1;
        for(int i=0;i<arr.size();i++)
        {
    
            int start=arr[i];
            int templen=1;
            for(int j=i+1;j<arr.size();j++)
            {
    
                if((start+difference)==arr[j])
                {
    
                    templen++;
                    start+=difference;
                }
            }
            maxlen=max(templen,maxlen);
        }
        cout<<maxlen<<endl;
        
        return maxlen;
    }
};
原网站

版权声明
本文为[I'm not xiaohaiwa~~~~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206231717527372.html