华为OD真题--跳格子

/**
* 跳格子游戏,小明和他朋友,每个格子有不一样的分数,不能回头跳,只能跳一圈
* 可以任意格子起跳,但是不能跳连续的格子
* 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];
    }

}

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

半生程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值