300. Longest Increasing Subsequence

Difficulty:
Related Topics:
Similar Questions:

Problem

Given an integer array nums, return **the length of the longest *strictly increasing subsequence***.

  Example 1:

Input: nums = [10,9,2,5,3,7,101,18]
Output: 4
Explanation: The longest increasing subsequence is [2,3,7,101], therefore the length is 4.

Example 2:

Input: nums = [0,1,0,3,2,3]
Output: 4

Example 3:

Input: nums = [7,7,7,7,7,7,7]
Output: 1

  Constraints:

  Follow up: Can you come up with an algorithm that runs in O(n log(n)) time complexity?

Solution

/**
 * @param {number[]} nums
 * @return {number}
 */
var lengthOfLIS = function(nums) {
    var arr = [nums[0]];
    for (var i = 1; i < nums.length; i++) {
        if (nums[i] > arr[arr.length - 1]) {
            arr.push(nums[i]);
        } else {
            var index = binarySearch(arr, nums[i]);
            arr[index] = nums[i];
        }
    }
    return arr.length;
};

var binarySearch = function(arr, num) {
    var left = 0;
    var right = arr.length - 1;
    while (left < right) {
        var mid = left + Math.floor((right - left) / 2);
        if (arr[mid] > num) {
            right = mid;
        } else if (arr[mid] === num) {
            return mid;
        } else {
            left = mid + 1;
        }
    }
    return left;
};

Explain:

nope.

Complexity: