---restore content starts---
Dynamic programming is the number of the longest ascending sequence (longestincreasingsubsequence) in an array, with the complexity of O (n^2).
For example: Array int arr[] = {7,3,5,9,4,6,8,10}, the longest ascending sequence should be 3,5,6,8,10 or 3,4,6,8,10, the final answer should be 5;
Dp[i] Represents the number of the longest ascending sequence at the end of the following Mark I in the array, then the original problem is converted in order to find the maximum value in all Dp[i] (0<=i<len);
And each dp[i] is the number of the longest ascending sequence in all sequences with the end of the following Mark I.
Import Java.util.Scanner;
public class Main
{
public static void Main (string[] args) throws Exception
{
Scanner sc = new Scanner (system.in);
while (Sc.hasnext ())
{
int n = sc.nextint ();
int[] arr = new Int[n];
for (int i= 0;i<n;i++)
{
Arr[i] = Sc.nextint ();
}
System.out.println (Maxlis (arr));
}
}
public static int Maxlis (int[] arr)
{
int max = 1;
int len = arr.length;
Int[] dp = new Int[len];
Dp[0] = 1;
for (int i=1;i<len;i++)
{
for (Int J =0;j<i;j++)
{
if (Arr[i]>arr[j])
Dp[i] = Math.max (dp[i],dp[j]+1);
}
max = Math.max (Dp[i],max);
}
return Max;
}
}
---restore content ends---
Interview Basics Algorithm Questions