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;
    }
};
相关推荐
Hi李耶9 分钟前
【LeetCode】4-寻找两个正序数组的中位数
算法·leetcode·职场和发展
图灵机z21 分钟前
【算法提高课】AcWing 1027. 方格取数 长期攻克提高课-day3(3/219)
算法
hans汉斯30 分钟前
计算机科学与应用|改进MeanShift算法在智能监控视频中的应用研究
图像处理·人工智能·功能测试·深度学习·算法·音视频
a1117761 小时前
中文优先的企业 RAG 知识库 开源项目
开发语言·开源·kotlin
2301_777998341 小时前
C/C++:预处理详解
c语言·c++
破z晓1 小时前
javascript 导出excel表
开发语言·javascript·excel
t-think1 小时前
C++类和对象详解(一)
开发语言·c++
西门啐血1 小时前
上位机开发之假装有设备,使用 C# 模拟串口设备
开发语言·mongodb·c#
一次旅行1 小时前
AutoAWQ完整实战:MIT激活感知AWQ量化,模型显存减半、推理提速且精度无损
人工智能·python·算法
ask_baidu1 小时前
python实现Doris的streamLoad
开发语言·python