【Lintcode】273. Test Strategy

题目地址:

https://www.lintcode.com/problem/test-strategy/description

有一场考试,总时间 120 120 120分钟,给定四个数组ppartffull,分别表示每道题如果只做一部分花的时间、得到的分数,和每道题做完整花的时间、得到的分数。问能得到的最大分数是多少。

思路是动态规划。设 g [ i ] [ t ] g[i][t] g[i][t]是如果只做第 0 0 0到第 i i i道题,在 t t t这么多时间内,能得到的最大分数。那么按照第 i i i道题怎么做,可以分为三类,一类是不做,一类是做部分,一类是做完整,则有: g [ i ] [ t ] = max ⁡ { g [ i − 1 ] [ t ] , g [ i − 1 ] [ t − p [ i ] ] + p a r t [ i ] , g [ i − 1 ] [ t − f [ i ] ] + f u l l [ i ] } g[i][t]=\max\{g[i-1][t],g[i-1][t-p[i]]+part[i],g[i-1][t-f[i]]+full[i]\} g[i][t]=max{g[i1][t],g[i1][tp[i]]+part[i],g[i1][tf[i]]+full[i]}初始条件是要求 g [ 0 ] [ t ] g[0][t] g[0][t],也可以分为上面三类,详细解释这里省略。代码如下:

public class Solution {
    /**
     * @param p:    The time you choose to do part of the problem.
     * @param part: The points you choose to do part of the problem.
     * @param f:    The time you choose to do the whole problem.
     * @param full: The points you choose to do the whole problem.
     * @return: Return the maximum number of points you can get.
     */
    public int exam(int[] p, int[] part, int[] f, int[] full) {
        // write your code here
        int n = p.length;
        int[][] dp = new int[n][121];
        // 枚举第0道题怎么处理
        for (int i = p[0]; i <= 120; i++) {
            dp[0][i] = part[0];
            if (i >= f[0]) {
                dp[0][i] = full[0];
            }
        }
        
        for (int i = 1; i < n; i++) {
            for (int j = 0; j <= 120; j++) {
            	// 接下来枚举第i题怎么处理。如果第i题不做,那答案就是dp[i - 1][j]
                dp[i][j] = dp[i - 1][j];
                // 枚举只做部分的情况
                if (j >= p[i]) {
                    dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - p[i]] + part[i]);
                }
                // 枚举做完整的情况
                if (j >= f[i]) {
                    dp[i][j] = Math.max(dp[i][j], dp[i - 1][j - f[i]] + full[i]);
                }
            }
        }
        
        return dp[n - 1][120];
    }
}

时空复杂度 O ( n ) O(n) O(n) n n n是题目数量。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值