Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2140. Solving Questions With Brainpower #122

Open
Woodyiiiiiii opened this issue May 17, 2022 · 0 comments
Open

2140. Solving Questions With Brainpower #122

Woodyiiiiiii opened this issue May 17, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

这道题涉及到选择的问题,又因为数据量10^5,所以肯定要用动态规划DP的。

如何使用DP解法呢?首先看到可以skip一道题,但要选择下一道题,可以联想到House Robber;但题目中涉及到brain power,选择了答对一道题就会有一定的冷却时间,也就是说会影响到后续的答题,直白点的话在每次题目遍历中要遍历之前的所有题判断冷却时间是否结束,那这样就要有O(n^2)级别的时间复杂度了。

所以关键是,从右往左去遍历数组,从而推出递推方程(看代码)。

class Solution {
    public long mostPoints(int[][] questions) {
        
        int n = questions.length;
        
        long[] dp = new long[n];
        
        for (int i = n - 1; i >= 0; --i) {
            if (i == n - 1) {
                dp[i] = questions[i][0];
            } else if (i + questions[i][1] + 1 >= n) {
                dp[i] = Math.max(dp[i + 1], questions[i][0]);
            } else {
                dp[i] = Math.max(dp[i + 1], dp[i + questions[i][1] + 1] + questions[i][0]);
            }
        }
        
        return dp[0];
        
    }
}

参考资料:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant