利用状态转移方程得到给定正数数组中不相邻元素子序列和的最大值

        Question:给定一个正数数组,找出不相邻元素的子序列的和的最大值。如:2、5、3、9应该返回14(5+9);8、5、3、9、1应该返回17(8+9);5 4 10 100 10 5应该返回110(5+100+5)

        要求:输入第一行为长度n  , 第二行为数组元素。

确定状态转移方程:vec[i] = max(vec[i]+vec[i-2],vec[i-1])


#include <stdio.h>

#define max(a,b) a>b?a:b

int find_max_sum_without_adjacents(int vec[],int N)
{
for (int i = 2; i <= N-1; i++)
{
if (i == 3)   // i ==3时为特例 需要单独拿出来比较
{
vec[i] = max(vec[i]+vec[i-2],vec[i]+vec[i-3]);
vec[i] = max(vec[i],vec[i-1]);
}
else 
{
vec[i] = max(vec[i]+vec[i-2],vec[i-1]);
}
}
return vec[N-1];
}


int main(int argc, char const *argv[])
{
int N;
scanf("%d",&N);
int c[N];
for (int j = 0; j < N; j++)
{
scanf("%d",&c[j]);
}
printf("%d\n",find_max_sum_without_adjacents(c,N));
return 0;
}

猜你喜欢

转载自blog.csdn.net/canger_/article/details/80215933