题解 | #不能连续吃草的牛II#
不能连续吃草的牛II
https://www.nowcoder.com/practice/0b6e9ca056eb4166b4bfd4f7c90b2c61
import java.util.*; public class Solution { /** 依然是利用动态规划的滑动窗口方法,降低了空间复杂度。 */ public int eatGrass (int[] nums) { // write code here if (nums.length == 1) { return nums[0]; } if (nums.length == 2) { return Math.max(nums[0], nums[1]); } int x1=nums[0],y1=Math.max(nums[0],nums[1]),z1=0; int x2=0,y2=nums[1],z2=0; for (int i = 2; i < nums.length - 1; i++) { z1 = Math.max(y1, x1 + nums[i]); x1=y1; y1=z1; z2 = Math.max(y2, x2 + nums[i]); x2=y2; y2=z2; } z2 = Math.max(y2, x2+ nums[nums.length-1]); return Math.max(z2, z1); } }