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;
    }
};
相关推荐
tkevinjd27 分钟前
C++中线程库的基本操作
开发语言·c++
CodeWithMe36 分钟前
【C/C++】不同防止头文件重复包含的措施
c语言·开发语言·c++
Fre丸子_44 分钟前
C++定长内存块的实现
c++
子豪-中国机器人1 小时前
C++ 信息学奥赛总复习题答案解析
开发语言·c++·算法
弥彦_1 小时前
牛客round95D
c++·算法
oioihoii1 小时前
C++11列表初始化:从入门到精通
java·开发语言·c++
zdy12635746881 小时前
python第48天打卡
开发语言·python
tomato091 小时前
2025 年中国大学生程序设计竞赛全国邀请赛(郑州)暨第七届CCPC河南省大学生程序设计竞赛(补题)
c++
whoarethenext1 小时前
使用 C++/OpenCV 创建动态流星雨特效 (实时动画)
开发语言·c++·opencv
whoarethenext1 小时前
使用 C/C++的OpenCV 实现模板匹配:从基础到优化
c语言·c++·opencv