LeetCode646. Maximum Length of Pair Chain——动态规划

文章目录

一、题目

You are given an array of n pairs pairs where pairs[i] = [lefti, righti] and lefti < righti.

A pair p2 = [c, d] follows a pair p1 = [a, b] if b < c. A chain of pairs can be formed in this fashion.

Return the length longest chain which can be formed.

You do not need to use up all the given intervals. You can select pairs in any order.

Example 1:

Input: pairs = [[1,2],[2,3],[3,4]]

Output: 2

Explanation: The longest chain is [1,2] -> [3,4].

Example 2:

Input: pairs = [[1,2],[7,8],[4,5]]

Output: 3

Explanation: The longest chain is [1,2] -> [4,5] -> [7,8].

Constraints:

n == pairs.length

1 <= n <= 1000

-1000 <= lefti < righti <= 1000

二、题解

cpp 复制代码
class Solution {
public:
    static bool cmp(vector<int>& a,vector<int>& b){
        return a[0] < b[0];
    }
    int findLongestChain(vector<vector<int>>& pairs) {
        int n = pairs.size(),len = 0;
        sort(pairs.begin(),pairs.end(),cmp);
        vector<int> ends(n,0);
        for(int i = 0;i < n;i++){
            int index = bs(ends,len,pairs[i][0]);
            if(index == -1) ends[len++] = pairs[i][1];
            else ends[index] = min(ends[index],pairs[i][1]);
        }
        return len;
    }
    int bs(vector<int>& ends,int len,int num){
        int l = 0,r = len - 1,res = -1;
        while(l <= r){
            int mid = (l + r) / 2;
            if(ends[mid] >= num){
                res = mid;
                r = mid - 1;
            }
            else l = mid + 1;
        }
        return res;
    }
};
相关推荐
沐雲小哥几秒前
bevfomer算法嵌入的tricks
数码相机·算法
wangzy1982几秒前
一个高效稳定的多边形三角化算法(支持自交和孤岛检测)
算法·图形渲染
添砖java‘’2 分钟前
序列与反序列化
服务器·网络·c++·序列化·反序列化
保持低旋律节奏2 分钟前
第三讲一元函数微分学的概念
算法
CrystalShaw2 分钟前
[AI codec]opus-1.6\dnn包含算法汇总和文件功能分类
人工智能·算法·dnn
南滑散修8 分钟前
机器学习(三):SVM支持向量机算法
算法·机器学习·支持向量机
AnalogElectronic8 分钟前
windows文件加解密工具,python实现,速度极快,篡改文件头尾信息以及还原
开发语言·windows·python
xyq202411 分钟前
《jQuery UI 设计主题》
开发语言
myloveasuka13 分钟前
Object&Objects
java·开发语言
sibylyue17 分钟前
JDK 17 +spiring boot+ maven 应用服务 高并发调优
java·开发语言·maven