給定一個整數數組(下標從 0 到 n-1, n 表示整個數組的規模),請找出該數組中的最長上升連續子序列。(最長上升連續子序列可以定義為從右到左或從左到右的序列。)
注意事項
time
您在真實的面試中是否遇到過這個題?
Yes
樣例
給定 [5, 4, 2, 1, 3], 其最長上升連續子序列(LICS)為 [5, 4, 2, 1], 返回 4.
給定 [5, 1, 2, 3, 4], 其最長上升連續子序列(LICS)為 [1, 2, 3, 4], 返回 4.
class Solution {
public:
/**
* @param A an array of Integer
* @return an integer
*/
int longestIncreasingContinuousSubsequence(vector<int>& A) {
// Write your code here
if(A.size()==0){
return 0;
}
if(A.size()==1){
return 1;
}
int maxlength1=0;
int length1=1;
for(int i=0;i<A.size()-1;i++){
int j=i+1;
if(A[i]<A[j]){
length1++;
}
else{
length1=1;
}
if(length1>maxlength1){
maxlength1=length1;
}
}
int maxlength2=0;
int length2=1;
for(int i=A.size()-1;i>0;i--){
int j=i-1;
if(A[j]>A[i]){
length2++;
}
else{
length2=1;
}
if(length2>maxlength2){
maxlength2=length2;
}
}
return maxlength2 > maxlength1 ? maxlength2:maxlength1;
}
};