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;
    }
};
相关推荐
乄夜几秒前
嵌入式面试高频(5)!!!C++语言(嵌入式八股文,嵌入式面经)
c语言·c++·单片机·嵌入式硬件·物联网·面试·职场和发展
夜晚回家11 分钟前
「Java基本语法」代码格式与注释规范
java·开发语言
YYDS31415 分钟前
C++动态规划-01背包
开发语言·c++·动态规划
前端页面仔25 分钟前
易语言是什么?易语言能做什么?
开发语言·安全
树叶@1 小时前
Python数据分析7
开发语言·python
wydaicls1 小时前
十一.C++ 类 -- 面向对象思想
开发语言·c++
Biomamba生信基地1 小时前
R语言基础| 下载、安装
开发语言·r语言·生信·医药
姜君竹1 小时前
QT的工程文件.pro文件
开发语言·c++·qt·系统架构
思捻如枫1 小时前
C++数据结构和算法代码模板总结——算法部分
数据结构·c++
奇树谦1 小时前
使用VTK还是OpenGL集成到qt程序里哪个好?
开发语言·qt