第一次自己写出动态规划的题(不容易,人类的智慧真不好理解(扣友的评论),哈哈);思路就不写了,大佬的题解已经很漂亮了
1 class Solution { 2 public int maxTurbulenceSize(int[] A) { 3 if(A == null || A.length == 0){ 4 return 0; 5 } 6 int maxans = 1; 7 int [] dp = new int[A.length]; 8 dp[0] = 1; 9 for(int i = 1; i < A.length; i++){ 10 11 if(i % 2 == 0 && A[i-1] > A[i]){//偶数 12 dp[i] = dp[i-1] + 1; 13 maxans = Math.max(dp[i],maxans); 14 }else if(i % 2 != 0 && A[i-1] < A[i]){ 15 dp[i] = dp[i-1] + 1; 16 maxans = Math.max(dp[i],maxans); 17 } 18 else{ 19 dp[i] = 1; 20 } 21 } 22 23 for(int i = 1; i < A.length; i++){ 24 25 if(i % 2 == 0 && A[i-1] < A[i]){//偶数 26 dp[i] = dp[i-1] + 1; 27 maxans = Math.max(dp[i],maxans); 28 }else if(i % 2 != 0 && A[i-1] > A[i]){ 29 dp[i] = dp[i-1] + 1; 30 maxans = Math.max(dp[i],maxans); 31 } 32 else{ 33 dp[i] = 1; 34 } 35 } 36 return maxans; 37 } 38 }
2020/9/8