Skip to content

Prepare For Coder Interview – Denny

  • Basic
  • Medium
  • Hard
  • Architect
  • Life

LeetCode: Longest Increasing Subsequence

Posted on March 14, 2018July 26, 2020 by braindenny

Longest Increasing Subsequence



Similar Problems:

  • CheatSheet: Leetcode For Code Interview
  • CheatSheet: Common Code Problems & Follow-ups
  • Tag: #dynamicprogramming, #lis

Given an unsorted array of integers, find the length of longest increasing subsequence.

For example,
Given [10, 9, 2, 5, 3, 7, 101, 18],
The longest increasing subsequence is [2, 3, 7, 101], therefore the length is 4. Note that there may be more than one LIS combination, it is only necessary for you to return the length.

Follow up: Could you improve it to O(n log n) time complexity?

Github: code.dennyzhang.com

Credits To: leetcode.com

Leave me comments, if you have better ways to solve.


// https://code.dennyzhang.com/longest-increasing-subsequence
// Basic Ideas: dynamic programming
//    dp(i): ends with nums[i]
// Complexity: Time O(n^2), Space O(n)
func lengthOfLIS(nums []int) int {
    res := 0
    l := make([]int, len(nums))
    for i, num := range nums {
        l[i] = 1
        if i != 0 {
            for j:=i-1; j>=0; j-- {
                if nums[j] < num {
                    if l[j] + 1 > l[i] {
                        l[i] = l[j]+1
                    }
                }
            }
        }
        if l[i] > res { res = l[i] }
    }
    return res
}
linkedin
github
slack

Post Views: 6
Posted in BasicTagged #dynamicprogramming, lis

Post navigation

LeetCode: Unique Binary Search Trees II
LeetCode: Subarray Product Less Than K

Leave a Reply Cancel reply

Your email address will not be published.

Tags

#array #backtracking #bfs #binarytree #bitmanipulation #blog #classic #codetemplate #combination #dfs #dynamicprogramming #game #graph #greedy #heap #inspiring #interval #linkedlist #manydetails #math #palindrome #recursive #slidingwindow #stack #string #subarray #trie #twopointer #twosum binarysearch editdistance hashmap intervaldp knapsack monotone oodesign presum rectangle redo review rotatelist series sql treetraversal unionfind

Recent Posts

  • a
  • a
  • a
  • a
  • a

Recent Comments

    Archives

    Categories

    • Amusing
    • Basic
    • Easy
    • Hard
    • Life
    • Medium
    • Resource
    • Review
    • Series
    • Uncategorized
    Proudly powered by WordPress | Theme: petals by Aurorum.