GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — leetcode/300.Longest Increasing Subsequence at master · geemo/leetcode

Expand file tree

/

300.Longest Increasing Subsequence

/
Copy path

Directory actions

More options

More options

Directory actions

More options

More options

Latest commit

 

History

History
History
/

300.Longest Increasing Subsequence

/
Copy path

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
README.md
README.md
 
 

README.md

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

Example:

Input: [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. 

Note:

  • There may be more than one LIS combination, it is only necessary for you to return the length.
  • Your algorithm should run in O(n2) complexity.

Solution:

func lengthOfLIS(nums []int) int {
	if len(nums) == 0 {
		return 0
	}

	size := len(nums)
	dp := make([]int, size)
	for i := 0; i < size; i++ {
		dp[i] = 1
	}

	for i := 0; i < size; i++ {
		for j := 0; j < i; j++ {
			if nums[j] < nums[i] {
				dp[i] = max(dp[i], dp[j] + 1)
			}
		}
	}

	lens := 1
	for _, l := range dp {
		lens = max(lens, l)
	}

	return lens
}

func max(a, b int) int {
	if a > b {
		return a
	}

	return b
}

binary search

func lengthOfLIS(nums []int) int {
	var piles int
	top := make([]int, len(nums))
	for _, pocker := range nums {
		left, right := 0, piles
		for left < right {
			mid := left + (right - left) / 2
			if top[mid] >= pocker {
				right = mid
			} else {
				left = mid + 1
			}
		}
		if left == piles {
			piles++
		}
		top[left] = pocker
	}

	return piles
}
You are visitor 01402520 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.