1
- /* A Naive Java Program for LIS Implementation */
2
- class LIS
3
- {
4
- static int max_ref ; // stores the LIS
5
-
6
- /* To make use of recursive calls, this function must return
7
- two things:
8
- 1) Length of LIS ending with element arr[n-1]. We use
9
- max_ending_here for this purpose
10
- 2) Overall maximum as the LIS may end with an element
11
- before arr[n-1] max_ref is used this purpose.
12
- The value of LIS of full array of size n is stored in
13
- *max_ref which is our final result */
14
- static int _lis (int arr [], int n )
15
- {
16
- // base case
17
- if (n == 1 )
18
- return 1 ;
19
-
20
- // 'max_ending_here' is length of LIS ending with arr[n-1]
21
- int res , max_ending_here = 1 ;
22
-
23
- /* Recursively get all LIS ending with arr[0], arr[1] ...
24
- arr[n-2]. If arr[i-1] is smaller than arr[n-1], and
25
- max ending with arr[n-1] needs to be updated, then
26
- update it */
27
- for (int i = 1 ; i < n ; i ++)
28
- {
29
- res = _lis (arr , i );
30
- if (arr [i -1 ] < arr [n -1 ] && res + 1 > max_ending_here )
31
- max_ending_here = res + 1 ;
32
- }
33
-
34
- // Compare max_ending_here with the overall max. And
35
- // update the overall max if needed
36
- if (max_ref < max_ending_here )
37
- max_ref = max_ending_here ;
38
-
39
- // Return length of LIS ending with arr[n-1]
40
- return max_ending_here ;
41
- }
42
-
43
- // The wrapper function for _lis()
44
- static int lis (int arr [], int n )
45
- {
46
- // The max variable holds the result
47
- max_ref = 1 ;
48
-
49
- // The function _lis() stores its result in max
50
- _lis ( arr , n );
51
-
52
- // returns max
53
- return max_ref ;
54
- }
55
-
56
- // driver program to test above functions
57
- public static void main (String args [])
58
- {
59
- int arr [] = { 10 , 22 , 9 , 33 , 21 , 50 , 41 , 60 };
60
- int n = arr .length ;
61
- System .out .println ("Length of LIS is "
62
- + lis (arr , n ) + "n" );
63
- }
1
+ class Solution {
2
+ // problem statement and judging: https://leetcode.com/problems/longest-increasing-subsequence
3
+ public int lengthOfLIS (int [] nums ) {
4
+ int len = nums .length ;
5
+
6
+ int [] dp = new int [len ];
7
+
8
+ for (int i =0 ; i <len ; ++i ) { dp [i ] = 1 ; }
9
+
10
+ for (int i =0 ; i <len ; ++i ) {
11
+ for (int j =0 ; j <i ; ++j ) {
12
+ if ( nums [j ] < nums [i ] ) {
13
+ dp [i ] = Math .max (dp [i ], dp [j ]+1 );
14
+ }
15
+ }
16
+ }
17
+
18
+ int max_dp = 1 ;
19
+ for (int i =1 ; i <len ; ++i ) {
20
+ max_dp = Math .max (dp [i ], max_dp );
21
+ }
22
+
23
+ return max_dp ;
24
+ }
64
25
}
0 commit comments