面试题 17.08. 马戏团人塔
原题链接
有个马戏团正在设计叠罗汉的表演节目,一个人要站在另一人的肩膀上。出于实际和美观的考虑,在上面的人要比下面的人矮一点且轻一点。已知马戏团每个人的身高和体重,请编写代码计算叠罗汉最多能叠几个人。
示例:
输入:height = [65,70,56,75,60,68] weight = [100,150,90,190,95,110]
输出:6
解释:从上往下数,叠罗汉最多能叠 6 层:(56,90), (60,95), (65,100), (68,110), (70,150), (75,190)
提示:
height.length == weight.length <= 10000
class Solution {
public:
int bestSeqAtIndex(vector<int>& height, vector<int>& weight) {
static auto speedup = [](){ios::sync_with_stdio(false);cin.tie(nullptr);return nullptr;}();
vector<pair<int, int> > arr;
vector<int> dp(height.size()+1, 0);
for (int i = 0; i < height.size(); ++i){
arr.push_back(make_pair(height[i], weight[i]));
}
sort(arr.begin(), arr.end(), [](pair<int,int> &a,pair<int,int> &b){
if (a.first == b.first) return a.second > b.second;
return a.first < b.first;
});
int res = 1;
dp[1] = arr.front().second;
for (int i = 1; i < arr.size(); ++i){
if (arr[i].second > dp[res]){
dp[++res] = arr[i].second;
}
else{
auto pos = lower_bound(dp.begin()+1,dp.begin()+res+1,arr[i].second);
*pos = arr[i].second;
}
}
return res;
}
};