300.最长递增子序列
300.最长递增子序列
题解
//state: dp[i]表示[0,i)的最长上升子序列
//function: dp[i] = max(dp[j])+1 —>nums[j]<nums[i] && j<i
//intialize:dp[i] = 1
//answer: max(dp[N])
代码
package main func lengthOfLIS(nums []int) int { dp := make([]int, len(nums)) for idx := range dp { dp[idx] = 1 } for i := 1; i < len(nums); i++ { for j := 0; j < i; j++ { if nums[j] < nums[i] { dp[i] = max(dp[i], dp[j]+1) } } } result := 0 for idx := range dp { result = max(result, dp[idx]) } return result } func max(a, b int) int { if a > b { return a } return b }