当前位置:网站首页>342 · 山谷序列
342 · 山谷序列
2022-07-30 07:53:00 【yinhua405】
描述
给你一个长度为nn的序列,在他的子序列中让你找一个山谷序列,山谷序列定义为:
- 序列的长度为偶数。
- 假设子序列的长度为2n2n。则前nn个数是严格递减的,后nn个数是严格递增的,并且第一段的最后一个元素和第二段的第一个元素相同,也是这段序列中的最小值。
现在想让你找所有子序列中满足山谷序列规则的最长的长度为多少?
背完这套刷题模板,真的不一样!
北大学霸令狐冲15年刷题经验总结的《算法小抄模板Cheat Sheet》助你上岸!
微信添加【jiuzhang0607】备注【小抄】领取
- 1<=len(num)<=10001<=len(num)<=1000
- 1<=num[i]<=100001<=num[i]<=10000
样例
样例 1:
输入: num = [5,4,3,2,1,2,3,4,5]
输出: 8
样例解释:
最长山谷序列为[5,4,3,2,2,3,4,5]
样例 2:
输入: num = [1,2,3,4,5]
输出: 0
样例解释:
不存在山谷序列
int valley(vector<int> &num) {
// write your code here
// write your code here
int size = num.size();
int left = 0;
int right = size - 1;
vector<int>dpleft(size, 0);
vector<int>dpright(size, 0);
map<int, set<int>> mapSet; //num[i],i
int leftMax = 0;
int rightMax = 0;
mapSet[num[left]] = set<int>{ 0};
//从左到右统计递减数量
for (int left = 1; left < size; left++)
{
auto it = mapSet.find(num[left]);
if (it != mapSet.end())
{
it->second.insert(left);
}
else
{
mapSet[num[left]] = set<int>{ left };
}
for (int i = left - 1; i >= 0; i--)
{
if (num[left] < num[i])
{
dpleft[left] = max(dpleft[left], dpleft[i] + 1);
if (dpleft[left] > leftMax)
{
leftMax = dpleft[left];
}
}
}
}
//从右到左统计递减数量
for (int right = size - 2; right >= 0; right--)
{
for (int j = right + 1; j < size; j++)
{
if (num[right] < num[j])
{
dpright[right] = max(dpright[right], dpright[j] + 1);
if (dpright[left] > rightMax)
{
rightMax = dpright[left];
}
}
}
}
int maxRet = 0;
for (int i = 0; i < size; i++)
{
if (mapSet[num[i]].size() <= 1)
{
continue;
}
set<int> tmp = mapSet[num[i]];
for (auto it : tmp)
{
if (it <= i)
{
continue;
}
int minTmp = min(dpleft[i], dpright[it]) +1;
if (minTmp > maxRet)
{
maxRet = minTmp;
}
}
}
return maxRet*2;
}
边栏推荐
猜你喜欢
随机推荐
经典毕业设计:基于SSM实现高校后勤报修系统
[Unity]UI切换环形滚动效果
【SQL server速成之路】——身份验证及建立和管理用户账户
Thinking about digital transformation of construction enterprises in 2022, the road to digital transformation of construction enterprises
SQL injection vulnerability (postgresql injection)
英语语法-名词性从句
typescript1-typescript是什么
Webview中的超链接点击到外部浏览器打开
研发转至FAE(现场应用工程师),是否远离技术了?有前途吗?
看完这100个客户需求,我终于知道企业文档管理的秘密
PCB板加工流程中哪些因素会影响到传输线阻抗
ACL 2022 | Introduce angular margin to construct comparative learning objectives and enhance text semantic discrimination ability
剖析SGI STL空间配置器(一 、辅助接口函数)
基于SSM实现高校后勤报修系统
阿里云国际版云服务器防火墙设置
The full arrangement of the 46th question in C language.Backtracking
ipset restore命令维护set,但原已存在的条目未删除掉
Windows 下安装 MySQL
test2
AutoSAR EcuM系列02- Fixed EcuM的状态管理





![[Mini Program Column] Summarize the development specifications of uniapp to develop small programs](/img/7b/110d324eba00652e4987bc623a5bc6.png)



