TopCoder-BadNeighbours

来源:互联网 发布:高仿买家退货淘宝介入 编辑:程序博客网 时间:2024/05/22 04:47

题目描述:http://community.topcoder.com/stat?c=problem_statement&pm=2402&rd=5009

题目大意:有N个人围成一个圈,第i个人愿意捐出donations[i]的钱,但是只要左右相邻有人捐款了,他就不会捐款,求最多的捐款数量。

思路:若是N个人排成一条线,用m[i]表示到第i个人为止,筹到的最多的钱。则m[i] = max{m[i-1],m[i-2]+donations[i]}。现在N个人排成一圈,可以这样考虑:1、0到n-2这么多人中筹到的钱;2、1到n-1这么多人中筹到的钱。取两者中最大的。


public class BadNeighbors {int dp(int[] donations,int from,int to){int[] ans = new int[to-from];ans[0] = donations[from];ans[1] = donations[from]>donations[from+1]? donations[from]:donations[from+1];for(int i = 2;i<ans.length;i++)ans[i] = ans[i-1]>ans[i-2]+donations[from+i]? ans[i-1]:ans[i-2]+donations[from+i];return ans[ans.length-1];}public int maxDonations(int[] donations){if(donations.length<=3){int max = -1;for(int i=0;i<donations.length;i++)max = donations[i]>max ? donations[i]:max;return max;}int ans1 = dp(donations,0,donations.length-1);int ans2 = dp(donations,1,donations.length);return  ans1>ans2?ans1:ans2;}}

0 0
原创粉丝点击