LintCode397:最長上升連續子數列
阿新 • • 發佈:2019-02-18
給定一個整數陣列(下標從 0 到 n-1, n 表示整個陣列的規模),請找出該陣列中的最長上升連續子序列。(最長上升連續子序列可以定義為從右到左或從左到右的序列。)
樣例
給定 [5, 4, 2, 1, 3], 其最長上升連續子序列(LICS)為 [5, 4, 2, 1], 返回 4.
給定 [5, 1, 2, 3, 4], 其最長上升連續子序列(LICS)為 [1, 2, 3, 4], 返回 4.
程式碼如下
public int longestIncreasingContinuousSubsequence(int[] A) {
// Write your code here
int len = A.length;
int max=0,temp=1;
if(len==0){
return 0;
}else if(len==1){
return 1;
}else{
for(int i=0;i<len-1;i++){
if(A[i]>A[i+1]){
temp++;
}else{
temp=1 ;
}
if(max<temp){
max=temp;
}
}
temp=1;
for(int i=0;i<len-1;i++){
if(A[i]<A[i+1]){
temp++;
}else{
temp=1;
}
if (max<temp){
max=temp;
}
}
}
return max;
}
這裡我是分別計算升序子數列和降序子數列的。