题解 | #不相邻取数#

不相邻取数

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

import java.io.*; public class Main{ public static void main(String[] args)throws IOException{ BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String str = null; while((str = in.readLine()) != null){ int n = Integer.parseInt(str); String[] arr = in.readLine().split(" "); int[] res = new int[n]; for(int i = 0;i < n;i++){ res[i] = Integer.parseInt(arr[i]); } if(n == 1){ System.out.println(res[0]); continue; } if(n == 2){ System.out.println(Math.max(res[0],res[1])); continue; } int[] dest = new int[n]; dest[0] = res[0]; dest[1] = res[1]; dest[2] = res[0] + res[2]; if (n == 3) { System.out.println(Math.max(dest[2],dest[1])); continue; } for(int i = 3; i < n;i++){ dest[i] = Math.max(dest[i-2],dest[i-3]) + res[i]; } System.out.println(Math.max(dest[n - 1],dest[n-2])); } } }

我居南半坡 文章被收录于专栏

多刷题,积蓄力量,欢迎讨论

全部评论

相关推荐

投递美团等公司10个岗位
点赞 评论 收藏
转发
点赞 收藏 评论
分享
牛客网
牛客企业服务