最大子序列总和使得没有三个是连续的
给定一系列正数,找到可以形成的最大总和,该总和不存在三个连续的元素。
Examples :
Input 1: arr[] = {1, 2, 3}
Output: 5
We can't take three of them, so answer is
2 + 3 = 5
Input 2: arr[] = {3000, 2000, 1000, 3, 10}
Output: 5013
3000 + 2000 + 3 + 10 = 5013
Input 3: arr[] = {100, 1000, 100, 1000, 1}
Output: 2101
100 + 1000 + 1000 + 1 = 2101
Input 4: arr[] = {1, 1, 1, 1, 1}
Output: 4
Input 5: arr[] = {1, 2, 3, 4, 5, 6, 7, 8}
Output: 27
Input 6: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Output: 40
#include<bits/stdc++.h>
using namespace std;
int findMax(vector<int>& nums, int k, vector<long long int>& dp)
{
if(k >= nums.size()) {
return 0;
}
if(dp[k]!=-1)
return dp[k];
int a=findMax(nums,k+1,dp); //exclude first element
int b=nums[k]+findMax(nums,k+2,dp); //exclude second element
int c=nums[k]+nums[k+1]+findMax(nums,k+3,dp); //exclude third element
dp[k]= max(a,max(b, c));
return dp[k];
}
int main()
{
vector<int>nums = {1, 2, 3, 4, 5, 6, 7, 8};
int n = nums.size();
vector<long long int>dp(n,-1);
cout<<findMax(nums,0,dp);
return 0;
}
有人可以告诉我此代码的错误是什么?输入1至5的运行良好。但是,第六次测试案例的输出速度为134,而不是40。为什么?
Given a sequence of positive numbers, find the maximum sum that can be formed which has no three consecutive elements present.
Examples :
Input 1: arr[] = {1, 2, 3}
Output: 5
We can't take three of them, so answer is
2 + 3 = 5
Input 2: arr[] = {3000, 2000, 1000, 3, 10}
Output: 5013
3000 + 2000 + 3 + 10 = 5013
Input 3: arr[] = {100, 1000, 100, 1000, 1}
Output: 2101
100 + 1000 + 1000 + 1 = 2101
Input 4: arr[] = {1, 1, 1, 1, 1}
Output: 4
Input 5: arr[] = {1, 2, 3, 4, 5, 6, 7, 8}
Output: 27
Input 6: arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Output: 40
#include<bits/stdc++.h>
using namespace std;
int findMax(vector<int>& nums, int k, vector<long long int>& dp)
{
if(k >= nums.size()) {
return 0;
}
if(dp[k]!=-1)
return dp[k];
int a=findMax(nums,k+1,dp); //exclude first element
int b=nums[k]+findMax(nums,k+2,dp); //exclude second element
int c=nums[k]+nums[k+1]+findMax(nums,k+3,dp); //exclude third element
dp[k]= max(a,max(b, c));
return dp[k];
}
int main()
{
vector<int>nums = {1, 2, 3, 4, 5, 6, 7, 8};
int n = nums.size();
vector<long long int>dp(n,-1);
cout<<findMax(nums,0,dp);
return 0;
}
Can somebody tell me what is the error with this code? Input 1 to 5 is running perfectly fine. But, the output for the sixth test case is coming as 134 instead of 40. Why is it so?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当
k == nums.size()-1
时,您的UB具有c
计算的限制访问。您必须处理案例,例如:
demo
When
k == nums.size() - 1
, you have UB with out of bound access withc
computation.You have to handle the case, for example:
Demo