题解 | #不相邻取数#

不相邻取数

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;
}
全部评论

相关推荐

牛油果甜奶昔:别的先不说,牛客还能内推护士?
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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