dp入门例题(1)

按摩师问题

https://leetcode-cn.com/problems/the-masseuse-lcci/

(找好状态转移方程) 

今天只和昨天的状态相关,依然是分类讨论:

    今天不接受预约:或者是昨天不接受预约,或者是昨天接受了预约,取二者最大值,即:dp[i][0] = max(dp[i - 1][0], dp[i - 1][1]);
    今天接受预约:只需要从昨天不接受预约转移而来,加上今天的时常,即:dp[i][1] = dp[i - 1][0] + nums[i]

 1 public class Solution {
 2 
 3     public int massage(int[] nums) {
 4         int len = nums.length;
 5         if (len == 0) {
 6             return 0;
 7         }
 8         if (len == 1) {
 9             return nums[0];
10         }
11 
12         // dp[i][0]:区间 [0, i] 里接受预约请求,并且下标为 i 的这一天不接受预约的最大时长
13         // dp[i][1]:区间 [0, i] 里接受预约请求,并且下标为 i 的这一天接受预约的最大时长
14         int[][] dp = new int[len][2];
15         dp[0][0] = 0;
16         dp[0][1] = nums[0];
17 
18         for (int i = 1; i < len; i++) {
19             dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1]);
20             dp[i][1] = dp[i - 1][0] + nums[i];
21         }
22         return Math.max(dp[len - 1][0], dp[len - 1][1]);
23     }
24 
25     public static void main(String[] args) {
26         Solution solution = new Solution();
27         // int[] nums = {1, 2, 3, 1};
28         // int[] nums = {2, 7, 9, 3, 1};
29         int[] nums = {2, 1, 4, 5, 3, 1, 1, 3};
30         int res = solution.massage(nums);
31         System.out.println(res);
32     }


作者:liweiwei1419
链接:https://leetcode-cn.com/problems/the-masseuse-lcci/solution/dong-tai-gui-hua-by-liweiwei1419-8/
来源:力扣(LeetCode)
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

原文地址:https://www.cnblogs.com/zhmlzhml/p/12639643.html