class Solution {
public int wiggleMaxLength(int[] nums) {
int count = 1;
int prev = 0;
int cur = 0;
for (int i=0; i<nums.length-1; i++) {
cur = nums[i+1]-nums[i];
if (prev <= 0 && cur > 0 || prev >= 0 && cur < 0) {
count++;
prev = cur;
}
}
return count;
}
}
方法2: DP
top[i] 到i位置是波峰的wiggle subsequence的最长长度
bottom[i]: 到i位置是波谷的wiggle subsequence的最长长度
return Math.max(top[nums.length-1], bottom[nums.length-1]); to find the max. wiggle subsequence length
Time Complexity: O(n)
Space Complexity: O(n) -> can use two int instead of two int[] to reduce space complexity
class Solution {
public int wiggleMaxLength(int[] nums) {
int[] top = new int[nums.length];
int[] bottom = new int[nums.length];
top[0] = 1;
bottom[0] = 1;
for (int i=1; i<nums.length; i++) {
if (nums[i] > nums[i-1]) {
top[i] = bottom[i-1]+1;
bottom[i] = bottom[i-1];
} else if (nums[i] < nums[i-1]) {
top[i] = top[i-1];
bottom[i] = top[i-1]+1;
} else {
top[i] = top[i-1];
bottom[i] = bottom[i-1];
}
}
return Math.max(top[nums.length-1],bottom[nums.length-1]);
}
}
class Solution {
public int maxSubArray(int[] nums) {
int max = Integer.MIN_VALUE;
int cur = 0;
for (int i=0; i<nums.length; i++) {
cur += nums[i];
if (cur > max) max = cur;
if (cur <= 0) cur = 0;
}
return max;
}
}
方法2: DP
dp[i] / cur: 包括i位置的subsequence的最大值
max: 当前所有subsequence的最大值
Time Complexity: O(n)
Space Complexity: O(n) -> can use int instead of int[] to reduce space complexity
class Solution {
public int maxSubArray(int[] nums) {
int[] dp = new int[nums.length];
dp[0] = nums[0];
int max = nums[0];
for (int i=1; i<nums.length; i++) {
dp[i] = Math.max(dp[i-1]+nums[i], nums[i]);
if (dp[i] > max) max = dp[i];
}
return max;
}
}
// Space Complexity: O(1)
class Solution {
public int maxSubArray(int[] nums) {
int cur = nums[0];
int max = nums[0];
for (int i=1; i<nums.length; i++) {
cur = Math.max(cur+nums[i], nums[i]);
if (cur > max) max = cur;
}
return max;
}
}