题解 | #不相邻取数#

不相邻取数

http://www.nowcoder.com/practice/a2be806a0e5747a088670f5dc62cfa1e

//不相邻取数,取数个数不定
#include <stdio.h>
#include <malloc.h>

int main(){
    int n = 0;
    scanf("%d", &n);
    int* ans = (int*)malloc(sizeof(int)*n);
    for (int i = 0; i < n; i++) {
        scanf("%d", &ans[i]);
    }
    int* temp = (int*)malloc(sizeof(int)*n);
    temp[0] = ans[0];
    temp[1] = ans[0] > ans[1] ? ans[0] : ans[1];
    for (int i = 2; i < n; i++) {
        temp[i] = ans[i] + temp[i - 2] > temp[i - 1] ? ans[i] + temp[i - 2] : temp[i - 1];
    }
    int max = temp[0];
    for (int i = 1; i < n; i++) {
        max = max > temp[i] ? max : temp[i];
    }
    printf("%d\n", max);
    return 0;
}
全部评论

相关推荐

不愿透露姓名的神秘牛友
07-10 15:58
投个小米提前批试试水,先投一个岗位看看形势,不行就再沉淀一下投第二个岗位,莫辜负
Java抽象带篮子:我嘞个骚刚,已经开始研发6g了吗
投递小米集团等公司7个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务