The longest increasing subsequence
300. Longest Increasing Subsequence (Medium)
Subject description:
Given an array, find its longest increasing subsequence
Analysis of ideas:
Dynamic programming, to define a storage array dp longest increasing subsequence length, dp [n-] represented by the end of the longest increasing sequence length sequence Sn. For an increasing subsequence {Si1, Si2, ..., Sim}, if im <n and Sim <Sn, In this case {Si1, Si2, ..., Sim, Sn} is an increasing sequence, increasing subsequence an increase in length. Incrementing sequence satisfying the above condition, the length of the longest increasing subsequence that is to find, together constitute a Sn containing Sn as the end of the longest increasing the length of the longest sequence in the sequence is incremented. Therefore dp [n] = max {dp [i] +1 | Si <Sn && i <n}.
Code:
public int lengthOfLIS(int []nums){
if(nums==null||nums.length==0)
return 0;
int []dp=new int [nums.length];
for(int i=0;i<nums.length;i++){
int max=1;
for(int j=0;j<i;j++){
if(nums[i]>nums[j]){
max=Math.max(max,dp[j]+1);
}
}
dp[i]=max;
}
int res=dp[0];
for(int i=1;i<nums.length;i++){
if(dp[i]>res)
res=dp[i];
}
return res;
}