I came across this question. Given an array containing only positive values, you want to maximize the sum of chosen elements under the constraint that no group of more than k chosen elements are adjacent. For example if input is 1 2 3 1 7 9 (n=6 and k =2). The output will be 21, which comes from picking the elements _ 2 3 _ 7 9. My simple DP solution is this
#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));
}
But I am not sure whether this is the efficient solution. Can the complexity be further reduced? Thanks for your help