第一行输入一个整数
表示城市个数。
第二行输入
个整数
表示到达城市1到n可以获得的金币数量(第0个城市无法获得金币)。
在一行上输出一个整数表示答案;如果无法到达第
个城市,则输出
。
10 -1 2 3 4 -9 -9 -1 3 -1 -1
9
最优的方法是:第 1 步:使用跳跃 3 的卡牌,从 0 跳到 3 ,获得 3 枚金币;第 2 步:使用跳跃 1 的卡牌,从 3 跳到 4 ,获得 4 枚金币,共有 7 枚金币;第 3 步:使用跳跃 4 的卡牌,从 4 跳到 8 ,获得 3 枚金币,共有 10 枚金币;第 4 步:使用跳跃 2 的卡牌,从 8 跳到 10 ,获得 -1 枚金币,共有 9 枚金币。
public class BigRichGame { public static void main(String[] args) { int[] cityCoin = {-1, 2, 3, 4, -9, -9, -1, 3, -1, -1, 10, -1, 20}; int result = getResult(cityCoin); if (result == Integer.MIN_VALUE) { System.out.println("没有合适的组合到达n城市"); } else { System.out.println("最大金币值:" + result); } } //将数组拆分成很多个10步 public static int getResult(int[] cityCoin) { int[] steps = {1, 2, 3, 4}; int res = 0; int l = cityCoin.length - 1; int r = -1; while (r < l) { int n = Math.min(r + 10, l); LinkedList<Integer> roundStep = new LinkedList<>(); int max = getGoldCoin(cityCoin, r, n, steps, r, roundStep); res += max; r += 10; } return res; } //每十步的最优解 public static int getGoldCoin(int[] cityCoin, int r, int n, int[] steps, int start, LinkedList<Integer> roundStep) { //如果已经到达n城市则不需要再往前,直接返回我所有拿到的值 if (r == n) { return cityCoin[n]; } int max = Integer.MIN_VALUE; for (int step : steps) { int next = r + step; //如果大于n则直接结束 if (next > n) { continue; } if (roundStep.contains(step)) { continue; } roundStep.add(step); int nextAns = getGoldCoin(cityCoin, next, n, steps, start, roundStep); int nowAns = r != start ? cityCoin[r] : 0; int ans = nextAns == Integer.MIN_VALUE ? Integer.MIN_VALUE : Math.max(max, nowAns + nextAns); max = Math.max(ans, max); roundStep.removeLast(); } return max; } }