import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return int整型 */ public int eatGrass (int[] nums) { // write code here if (nums.length == 0) { return 0; } else if (nums.length == 1) { return nums[0]; } else if (nums.length == 2) { return Math.max(nums[0], nums[1]); } else if (nums.length == 3) { return Math.max(nums[0] + nums[2], nums[1]); } int grass = Math.max(nums[0] + nums[2], nums[1]); nums[2]+=nums[0]; for(int i=3;i<nums.length;i++){ nums[i] = Math.max(nums[i-2],nums[i-3])+nums[i]; grass = Math.max(grass,nums[i]); } return grass; } }
本题主要考察的知识点就是动态规划,所用编程语言是java。
我们只需要明白当前位置的最大值等于前两个位置和前三个位置两者之间的最大值加上当前位置值,此题就迎难而解了