Wiggle Subsequence

最长扭动子序列

思路1:动态规划。状态dp[i]表示以nums[i]为末尾的最长wiggle子序列的长度。时间是O(n^2).

 1 public class Solution {
 2     public int wiggleMaxLength(int[] nums) {
 3         if (nums == null || nums.length == 0) {
 4             return 0;
 5         }
 6         int[] pos_dp = new int[nums.length];
 7         int[] neg_dp = new int[nums.length];
 8         
 9         pos_dp[0] = 1;
10         neg_dp[0] = 1;
11         for (int i = 1; i < pos_dp.length; i++) {
12             neg_dp[i] = 1;
13             pos_dp[i] = 1;
14             for (int j = 0; j < i; j++) {
15                 if (nums[j] > nums[i]) {
16                     neg_dp[i] = Math.max(neg_dp[i], pos_dp[j] + 1);
17                 } else if (nums[j] < nums[i]) {
18                     pos_dp[i] = Math.max(pos_dp[i], neg_dp[j] + 1);
19                 }
20             }
21         }
22         
23         int res = 0;
24         for (int i = 0; i < pos_dp.length; i++) {
25             res = Math.max(Math.max(pos_dp[i], neg_dp[i]), res);
26         }
27         return res;
28     }
29 }
View Code

相关文章:

  • 2022-12-23
  • 2021-07-30
  • 2021-11-19
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-08-13
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-05-13
  • 2021-09-17
  • 2019-05-21
  • 2022-12-23
  • 2021-10-26
相关资源
相似解决方案