C 求数组中相邻元素不超过k个的元素的最大和的算法
我遇到了这个问题。给定一个仅包含正值的数组,您希望在相邻的选定元素组不超过k个的约束下,最大化选定元素的总和。例如,如果输入为123179(n=6,k=2)。输出将为21,这来自拾取元素2 3 7 9。我的简单DP解决方案是C 求数组中相邻元素不超过k个的元素的最大和的算法,c,algorithm,dynamic-programming,C,Algorithm,Dynamic Programming,我遇到了这个问题。给定一个仅包含正值的数组,您希望在相邻的选定元素组不超过k个的约束下,最大化选定元素的总和。例如,如果输入为123179(n=6,k=2)。输出将为21,这来自拾取元素2 3 7 9。我的简单DP解决方案是 #include<stdio.h> #include<limits.h> #include<malloc.h> long maxsum(int n,int k,long *sums){ long *maxsums; m
#include<stdio.h>
#include<limits.h>
#include<malloc.h>
long maxsum(int n,int k,long *sums){
long *maxsums;
maxsums = malloc(sizeof(long)*n);
int i;
long add = 0;
for(i=n-1;i>=n-k;i--){
add += sums[i];
maxsums[i] = add;
}
for(i = n-k-1;i>=0;i--){
int j;
long sum =0,max = 0,cur;
for(j=0;j<=k;j++){
cur = sum;
if((i+j+1)<n)
cur += maxsums[i+j+1];
if(cur > max) max = cur;
sum += sums[i+j];
}
maxsums[i] = max;
}
return maxsums[0];
}
int main(){
int cases=0,casedone=0;
int n,k;
long *array;
long maxsum = 0;
fscanf(stdin,"%d %d",&n,&k);
array = malloc(sizeof(long)*n);
int i =0;
while(casedone < n){
fscanf(stdin,"%ld",&array[casedone]);
casedone++;
}
printf("%ld",maxsum(n,k,array));
}
#包括
#包括
#包括
长最大和(整数n,整数k,长*和){
长*最大和;
maxsums=malloc(sizeof(long)*n);
int i;
长加=0;
对于(i=n-1;i>=n-k;i--){
加+=和[i];
最大和[i]=相加;
}
对于(i=n-k-1;i>=0;i--){
int j;
长和=0,最大值=0,cur;
对于(j=0;j我认为这会起作用:
findMaxSum(int a[], int in, int last, int k) { // in is current index, last is index of last chosen element
if ( in == size of a[] ) return 0;
dontChoseCurrent = findMaxSum(a, in+1, last, k); // If current element is negative, this will give better result
if (last == in-1 and k > 0) { // last and in are adjacent, to chose this k must be greater than 0
choseCurrentAdjacent = findMaxSum(a, in+1, in, k-1) + a[in];
}
if (last != in-1) { // last and in are not adjacent, you can chose this.
choseCurrentNotAdjacent = findMaxSum(a, in+1, in, k) + a[in];
}
return max of dontChoseCurrent, choseCurrentAdjacent, choseCurrentNotAdjacent
}
你的代码是正确的(至少思想是正确的),而且,到目前为止,我还没有发现任何错误的测试数据。按照你的想法,我们可以列出DP方程
p(v)=max{sum(C[v]~C[v+i-1])+p(v+i+1),0“不能拾取超过k个相邻元素”令人困惑。您的意思是“不能拾取超过k个元素,并且它们必须是相邻的”还是“可以拾取任意数量的元素,只要相邻的组不超过k个”?我更新了问题,从示例中可以清楚地看出,他指的是后者。这是作业吗?如果是的话,它应该被标记为这样。完全相同的问题已经讨论过了。通过得到这个问题的解决方案,你得到了什么?抱歉..我无法理解你的算法..无论如何,它是递归的..它看起来比我的复杂。。