/**
* 跳格子游戏,小明和他朋友,每个格子有不一样的分数,不能回头跳,只能跳一圈
* 可以任意格子起跳,但是不能跳连续的格子
* 1<= nums.length <= 100
* 1<= nums[i] <= 100
* 如:1 2 3 4 1 输出 1+ 3 = 4,只能跳前三个 第一格跟第四格已经收尾相连了
* 如:1 2 3 4 0 5 6 7 10 1
* 注意点:相隔的分数,跟隔开距离大于1的分数
*/
提供了2种解法:
1. 是双层循环遍历
2. 是动态规则
注:没有完整的测试用例,所以不确定对错,仅供参考。
public class Hopscotch {
public static void main(String[] args) {
int score[] = Arrays.asList("1 2 3 4 12 5 6 7 10 15 13 1".split(" ")).stream().mapToInt(Integer ::parseInt).toArray();
int[] p = loopMaxScore(score);
if (p == null) return;
int maxScore = Arrays.stream(p).max().getAsInt();
System.out.println("1:" + maxScore);
int dpScore = DpMaxScore(score);
System.out.println("2:" + dpScore);
}
/**
* 双层遍历循环
* @param score
* @return
*/
private static int[] loopMaxScore(int[] score) {
if (score.length == 1){
System.out.println(score[0]);
return score;
}
int p [] = new int[score.length];
p[0] = 0;
//每个数 都成为第一个起跳点,
for (int j = 0; j < score.length ; j ++){
for (int i = j; i < score.length; i = i+2){
if (i >= score.length){
break;
}
p[j] = p[j] + score[i];
}
}
return p;
}
/**
* 动态规划
* @param score
* @return
*/
public static int DpMaxScore(int[] score) {
int n = score.length;
if (n == 0) {
return 0;
}
int[] dp = new int[n];
dp[0] = score[0];
dp[1] = Math.max(score[0], score[1]);
for (int i = 2; i < n; i++) {
dp[i] = Math.max(dp[i-1], dp[i-2] + score[i]);
}
return dp[n-1];
}
}