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

文章目录

一、题目

You are given an array of n pairs pairs where pairsi = 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;
    }
};
相关推荐
看浪的路人21 分钟前
第2讲:一致性哈希——数据分片与负载均衡
算法·哈希算法
君顾122 分钟前
代驾跑腿业务系统实战开发指南
java·开发语言·代驾跑腿
夏幻灵40 分钟前
从语法坑点到 JS 内存底层:Vue 3 watch 侦听器深度全解
开发语言·javascript·vue.js
阿维的博客日记41 分钟前
保姆级教程介绍分词算法BPE
人工智能·算法·分词算法·bpe
Tongzhi20261 小时前
通芝科技无感考勤一体机:软硬一体,开箱即用
数据结构·数据库·科技·算法·均值算法·数据库开发
k4m7v2pz1 小时前
Rust 长跑守护进程日志治理:切分、时区与结构化
开发语言·后端·rust·日志系统·日志轮转·ndjson
FfHUCisI1 小时前
Golang RESTful API 设计原则
开发语言·golang·restful
breeze jiang1 小时前
ESLint flat config 配置实战:五大字段、规则严重级别与 --fix 能力边界详解
开发语言·前端·javascript
地平线开发者1 小时前
BEVdet模型解析
算法·自动驾驶
weixin_307779132 小时前
PHP 大文件上传:内存占用、超时与最佳实践
linux·服务器·开发语言·nginx·php