Advertisement
1988coder

673. Number of Longest Increasing Subsequence

Dec 29th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.06 KB | None | 0 0
  1.  
  2. // LeetCode URL: https://leetcode.com/problems/number-of-longest-increasing-subsequence/
  3. import java.util.Arrays;
  4.  
  5. /**
  6.  * Dynamic Programming
  7.  *
  8.  * Lengths[i] = Longest Increasing Subsequence known at i (including ith
  9.  * element)
  10.  *
  11.  * Counts[i] = Count of longest Increasing Subsequence known at i (including ith
  12.  * element)
  13.  *
  14.  * for nums[i] > nums[j] ... 0 <= j < i, if lengths[i] == lengths[j]+1 ... then
  15.  * just add nums[i] to the subsequence ending at jth position. Thus, add the
  16.  * counts of the subsequences with the same max length known at i.
  17.  *
  18.  * If lengths[i] < length[j] + 1.. then new max Length at i is found... thus
  19.  * update the length and counts at i.
  20.  *
  21.  * Time Complexity: O(N^2)
  22.  *
  23.  * Space Complexity: O(N)
  24.  *
  25.  * N = Length of input nums array.
  26.  */
  27. class Solution {
  28.     public int findNumberOfLIS(int[] nums) {
  29.         if (nums == null) {
  30.             return 0;
  31.         }
  32.         if (nums.length <= 1) {
  33.             return nums.length;
  34.         }
  35.  
  36.         int[] lengths = new int[nums.length];
  37.         int[] counts = new int[nums.length];
  38.         Arrays.fill(lengths, 1);
  39.         Arrays.fill(counts, 1);
  40.  
  41.         int maxCount = 1;
  42.         int maxLen = 1;
  43.  
  44.         for (int i = 1; i < nums.length; i++) {
  45.             for (int j = 0; j < i; j++) {
  46.                 if (nums[i] > nums[j]) {
  47.                     if (lengths[i] == lengths[j] + 1) {
  48.                         // Just adding the counts of the subsequences with same max length known at i.
  49.                         counts[i] += counts[j];
  50.                     } else if (lengths[i] < lengths[j] + 1) {
  51.                         // New max length at i is found.
  52.                         lengths[i] = lengths[j] + 1;
  53.                         counts[i] = counts[j];
  54.                     }
  55.                 }
  56.             }
  57.             if (maxLen == lengths[i]) {
  58.                 maxCount += counts[i];
  59.             } else if (maxLen < lengths[i]) {
  60.                 maxLen = lengths[i];
  61.                 maxCount = counts[i];
  62.             }
  63.         }
  64.  
  65.         return maxCount;
  66.     }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement