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;
    }
};
相关推荐
兵哥工控3 分钟前
MFC实现 Modbus-TCP 实时采集ZH-T08R 电阻模块阻值实例
c++·tcp/ip·mfc·modbus-tcp
普马萨特4 分钟前
Uber H3:地理网格索引在空间数据分析中的应用
数据结构·算法
alphaTao8 分钟前
LeetCode 每日一题 2026/5/11-2026/5/17
算法·leetcode
洛水水8 分钟前
【力扣100题】45.零钱兑换
算法·leetcode·职场和发展
cndes10 分钟前
Pycharm的虚拟环境设置问题
开发语言·python
河阿里20 分钟前
Java包装类(Wrapper):自动装箱拆箱机制与类型转换的那些坑
java·开发语言
jekc86826 分钟前
金蝶云星空调用第三方接口
开发语言·python
专注VB编程开发20年32 分钟前
json和python元组,列表,字典对比
开发语言·python·json·php
ComputerInBook34 分钟前
C++ 14 相比 C++ 11新增之特征
开发语言·c++·c++ 14
Aaron158839 分钟前
全频段 SDR干扰源模块解决方案(星链干扰、LORA无人机干扰)
人工智能·算法·fpga开发·硬件架构·硬件工程·无人机·信息与通信