Related topics :
Title description :
Given a sequence of length N, find the longest length of the subsequence whose value is strictly monotonically increasing.
Input format
The first line contains the integer N.
The second line contains N integers, representing the complete sequence.
Output format
Output an integer, indicating the maximum length. ,
data range
1≤N≤1000,
负十的九次方≤数列中的数≤十的九次方
**输入样例:**
7
3 1 2 1 8 5 6
Sample output:
4
Ideas
1.每一个数字都能单独作为一个上升子序列
其长度为1;
2.这题可以有两种解法一种是从左往右求上
升,还有一种是从右往左求最长下降子序列,
逻辑差不多,改点细节就可以了;
Code
method one from left to right
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int n=input.nextInt();
int arr[]=new int[n+1];
int ans=0;
for(int i=1;i<=n;i++){
arr[i]=input.nextInt();
}
int f[]=new int [n+1];
for(int i=1;i<=n;i++){
//自己本身就是一个子序列
f[i]=1;
for(int j=1;j<i;j++){
//f[i]表示第以第i个数为结尾的最长上升子序列
if(arr[i]>arr[j])
f[i]=Math.max(f[i],f[j]+1);
}
ans=Math.max(f[i],ans);
}
System.out.println(ans);
}
}
Method two from right to left
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int n=input.nextInt();
int arr[]=new int[n+1];
int ans=0;
for(int i=1;i<=n;i++){
arr[i]=input.nextInt();
}
int f[]=new int [n+1];
//从右往左求,即先求以最后一个数字为结尾的最长下降子序列
//这个时候需要反着看虽然i变小但是n~i的区间一直是变大的
for(int i=n;i>=1;i--){
f[i]=1; //在最开始以第i个数为结尾的最长子序列就是它自己,
//它要向前找看看没有没有比第i个数大且最长子序列大于它的数
for(int j=n;j>i;j--){
//我们求的是最长下降,所以是小于
if(arr[i]<arr[j])
f[i]=Math.max(f[i],f[j]+1);
}
ans=Math.max(f[i],ans);
}
System.out.println(ans);
}
}